Quickstart
Get AuthVault running in under 5 minutes. Install the package, initialize with your secret key, and you're ready to generate and verify tokens.
const AuthVault = require('authvault-sdk'); // Initialize with your secret const auth = new AuthVault({ secret: process.env.AUTH_SECRET, expiresIn: '7d', algorithm: 'HS256' }); // Generate a token for a user const token = await auth.generateToken({ userId: 'usr_abc123', role: 'admin' }); // Verify incoming token const payload = await auth.verifyToken(token); console.log(payload.userId); // 'usr_abc123'
Configuration
Pass a config object when initializing AuthVault. All options except secret have sensible defaults.
| Option | Type | Default | Description |
|---|---|---|---|
| secretrequired | string | — | Secret key for signing tokens. Use a long, random string in production. |
| expiresInoptional | string | 24h | Token lifetime. Accepts 60s, 7d, 1y etc. |
| algorithmoptional | string | HS256 | Signing algorithm. Supports HS256, HS512, RS256. |
| issueroptional | string | — | Token issuer claim (iss). Useful for multi-tenant apps. |
| audienceoptional | string | — | Intended token audience (aud). Validated on verify. |
Methods
Creates and signs a new JWT token with the provided payload. Returns the signed token string.
| Parameter | Type | Description |
|---|---|---|
| payload.userIdrequired | string | Unique identifier for the user. |
| payload.roleoptional | string | User role, e.g. admin, user, viewer. |
| payload.metaoptional | object | Any extra data to embed in the token. |
const token = await auth.generateToken({ userId: 'usr_xyz', role: 'editor', meta: { plan: 'pro' } }); // → "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
Validates a token's signature and expiry. Returns the decoded payload on success, throws AuthVaultError on failure.
⚠️ Always wrap verifyToken() in a try/catch block. An invalid or expired token throws rather than returning null.
try { const payload = await auth.verifyToken(token); console.log(payload.userId, payload.role); } catch (err) { if (err.code === 'TOKEN_EXPIRED') { // Prompt user to refresh } }
Issues a new token from an existing one without requiring the user to log in again. The original token is automatically revoked after refresh.
const newToken = await auth.refreshToken(expiredToken); // Returns fresh token with same payload, new expiry
Adds the token to an in-memory blocklist. Revoked tokens will fail verification even if not yet expired. Call this on user logout.
auth.revokeToken(token); // Token immediately invalidated
Error Codes
All errors are instances of AuthVaultError with a code and message property.
| Code | Description |
|---|---|
| TOKEN_EXPIRED | Token has passed its expiry time. Refresh or re-authenticate. |
| TOKEN_INVALID | Signature verification failed. Token may be tampered with. |
| TOKEN_REVOKED | Token was explicitly revoked via revokeToken(). |
| PAYLOAD_MISSING | No payload passed to generateToken(). |
| SECRET_REQUIRED | AuthVault was initialized without a secret key. |
Full Express.js Example
A complete authentication middleware using AuthVault in an Express.js application.
const express = require('express'); const AuthVault = require('authvault-sdk'); const app = express(); const auth = new AuthVault({ secret: process.env.AUTH_SECRET }); // Middleware to protect routes async function requireAuth(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).json({ error: 'No token provided' }); try { req.user = await auth.verifyToken(token); next(); } catch (err) { res.status(401).json({ error: err.message, code: err.code }); } } // Protected route app.get('/dashboard', requireAuth, (req, res) => { res.json({ message: `Welcome, ${req.user.userId}` }); });