jwt-express-helper
v1.0.0
Published
A lightweight helper for JSON Web Token (JWT) management and Express authentication middleware.
Maintainers
Readme
jwt-express-helper
A simple, lightweight helper library for signing/verifying JSON Web Tokens (JWT) and securing Express routes with a robust authentication middleware.
Features
- 🔑 Token Signing & Verification — wrappers around
jsonwebtokenfor quick token management. - 🛡️ Express Middleware — secure any endpoint with an easy-to-use middleware.
- 🍪 Automatic Token Extraction — automatically detects and extracts tokens from:
Authorization: Bearer <token>header- Cookies (cookie-parser / signedCookies)
- Query parameters (e.g.
?token=<token>) - Request body parameters (e.g.
req.body.token)
- ⚙️ Flexible Configuration — customize cookies name, request property name (e.g.
req.userorreq.auth), and credentials requirements (optional authentication). - 🎨 Custom Error Handling — intercept authentication errors and respond with custom JSON payloads.
Installation
npm install jwt-express-helperUsage
1. Basic JWT Signing and Verification
const { signToken, verifyToken } = require('jwt-express-helper');
const secret = 'super-secret-key';
const userPayload = { id: 101, role: 'admin' };
// Sign Token
const token = signToken(userPayload, secret, { expiresIn: '1h' });
console.log('Token:', token);
// Verify Token
const decoded = verifyToken(token, secret);
console.log('Decoded Payload:', decoded);2. Express Route Authentication Middleware
const express = require('express');
const { authMiddleware } = require('jwt-express-helper');
const app = express();
const JWT_SECRET = 'your-jwt-secret-key';
// Secure routes with authMiddleware
app.get('/api/dashboard', authMiddleware({ secret: JWT_SECRET }), (req, res) => {
// Decoded payload is attached to req.user by default
res.json({
message: 'Welcome to the dashboard!',
userId: req.user.id,
role: req.user.role
});
});
// Optional authentication route (will not throw error if token is missing/invalid)
app.get('/api/articles', authMiddleware({ secret: JWT_SECRET, credentialsRequired: false }), (req, res) => {
const user = req.user; // Will be defined only if token is valid
res.json({
user: user || null,
articles: ['Article 1', 'Article 2']
});
});Middleware Options
authMiddleware(options) accepts the following properties:
| Option | Type | Default | Description |
|---|---|---|---|
| secret | string | Required | Secret key to verify the signature of incoming tokens. |
| requestProperty | string | 'user' | Key on the req object where the decoded payload will be saved (e.g. req.user). |
| cookieName | string | 'token' | Name of the cookie containing the JWT if using cookies. |
| credentialsRequired | boolean | true | If true, throws error for missing/invalid token. If false, passes to next middleware. |
| getToken | Function | Default Extractor | Custom token extractor function (req) => string | null. |
| onError | Function | JSON 401 response | Custom error handling middleware (err, req, res, next) => void. |
License
MIT
