v3.2.0

AuthVault
SDK Docs

A lightweight Node.js SDK for token-based authentication, session management, and role-based access control. Drop it in and be secure in minutes.

Node.js JWT + OAuth TypeScript Ready Zero Dependencies
# Install via npm
npm install authvault-sdk

# Or with yarn
yarn add authvault-sdk

# Initialize
const AuthVault = require('authvault-sdk');
const auth = new AuthVault({ secret: 'your-secret' });

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.

JavaScript
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.

OptionTypeDefaultDescription
secretrequiredstringSecret key for signing tokens. Use a long, random string in production.
expiresInoptionalstring24hToken lifetime. Accepts 60s, 7d, 1y etc.
algorithmoptionalstringHS256Signing algorithm. Supports HS256, HS512, RS256.
issueroptionalstringToken issuer claim (iss). Useful for multi-tenant apps.
audienceoptionalstringIntended token audience (aud). Validated on verify.

Methods

async auth.generateToken( payload )

Creates and signs a new JWT token with the provided payload. Returns the signed token string.

ParameterTypeDescription
payload.userIdrequiredstringUnique identifier for the user.
payload.roleoptionalstringUser role, e.g. admin, user, viewer.
payload.metaoptionalobjectAny extra data to embed in the token.
Returns → string
const token = await auth.generateToken({
  userId: 'usr_xyz',
  role: 'editor',
  meta: { plan: 'pro' }
});
// → "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
async auth.verifyToken( token )

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.

Example
try {
  const payload = await auth.verifyToken(token);
  console.log(payload.userId, payload.role);
} catch (err) {
  if (err.code === 'TOKEN_EXPIRED') {
    // Prompt user to refresh
  }
}
async auth.refreshToken( token )

Issues a new token from an existing one without requiring the user to log in again. The original token is automatically revoked after refresh.

Example
const newToken = await auth.refreshToken(expiredToken);
// Returns fresh token with same payload, new expiry
sync auth.revokeToken( token )

Adds the token to an in-memory blocklist. Revoked tokens will fail verification even if not yet expired. Call this on user logout.

Example
auth.revokeToken(token);
// Token immediately invalidated

Error Codes

All errors are instances of AuthVaultError with a code and message property.

CodeDescription
TOKEN_EXPIREDToken has passed its expiry time. Refresh or re-authenticate.
TOKEN_INVALIDSignature verification failed. Token may be tampered with.
TOKEN_REVOKEDToken was explicitly revoked via revokeToken().
PAYLOAD_MISSINGNo payload passed to generateToken().
SECRET_REQUIREDAuthVault was initialized without a secret key.

Full Express.js Example

A complete authentication middleware using AuthVault in an Express.js application.

Express Middleware
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}` });
});