- Why express-authx?
- Installation
- Quick Usage
- Role-Based Access
- MongoDB Token Blacklisting
- MongoDB Session Storage
- TypeScript Support
- CLI Usage
A simple, fully-configurable authentication kit for Express.js apps using JWT, Refresh Tokens, Role-Based Access Control (RBAC), MongoDB sessions, and a powerful CLI – all in TypeScript.
Most authentication libraries either:
- Tie you to a third-party service (like Auth0 or Firebase),
- Require too much boilerplate (like Passport.js),
- Or lack refresh/session support entirely (like
jsonwebtokenalone).
express-authx solves that by giving you:
- Full control over your auth logic
- Access token support via Bearer headers and HTTP-only cookies
- Secure access & refresh token support
- Role-based route protection
- Optional Mongodb-based session management
- Powerful CLI for token generation & testing
- Written in TypeScript, supports JS
npm install express-authxCreate a .env file in your project root and define:
ACCESS_SECRET=your-access-secret
REFRESH_SECRET=your-refresh-secret
MONGO_URI=mongodb://localhost:27017These are used to securely sign & verify tokens.
import express from 'express';
import cookieParser from 'cookie-parser';
import { TokenManager, authMiddleware, MongoTokenBlacklist } from 'express-authx';
const app = express();
app.use(express.json());
app.use(cookieParser());
const tokenManager = new TokenManager(
{ secret: process.env.ACCESS_SECRET!, expiresIn: '15m' },
{ secret: process.env.REFRESH_SECRET!, expiresIn: '7d' }
);
const blacklist = new MongoTokenBlacklist(process.env.MONGO_URI!);
// IMPORTANT: Initialize MongoTokenBlacklist before use
await blacklist.init();
app.post('/login', (req, res) => {
const { id, role } = req.body;
const tokens = tokenManager.signTokens({ id, role });
res.cookie('accessToken', tokens.accessToken, { httpOnly: true });
res.cookie('refreshToken', tokens.refreshToken, { httpOnly: true });
res.json(tokens);
});
app.get('/profile', authMiddleware(tokenManager, blacklist), (req, res) => {
res.json({ message: 'Welcome', user: req.user });
});import { protectMiddleware } from 'express-authx';
app.get('/admin', protectMiddleware(['admin']), (req, res) => {
res.send('Admins only');
});import { MongoTokenBlacklist } from 'express-authx';
const blacklist = new MongoTokenBlacklist(process.env.MONGO_URI!);
await blacklist.init();
await blacklist.blacklistToken(token, expiryInSeconds);import { MongoSessionStore } from 'express-authx';
const sessionStore = new MongoSessionStore(process.env.MONGO_URI);
await sessionStore.saveSession({
userId: 'demoUser',
sessionId: 'uuid-session-id',
ip: '::1',
userAgent: 'browser-info',
createdAt: new Date(),
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
});Note: If you're using plain JavaScript, req.user is available without any additional setup.
If you're using TypeScript, you need to tell Express that your req.user property exists.
Create a file like types/express-authx.d.ts in your project:
// types/express-authx.d.ts
import 'express';
import type { TokenPayload } from 'express-authx';
declare module 'express-serve-static-core' {
interface Request {
user?: TokenPayload;
}
}Then include this file in your tsconfig.json:
{
"compilerOptions": {
"typeRoots": ["./types", "./node_modules/@types"]
}
}The CLI saves you time while developing or testing. Use it to generate, decode, or refresh tokens instantly. This CLI provides 6 core commands
Run any command below with
npx express-authxOR install globally withnpm i -g express-authx.
Purpose: Generate a new access and refresh token for a user.
npx express-authx create-user --id <user-id> --role <user-role>npx express-authx create-user --id=joe --role=adminYou’ll get:
✅ User created!
Access Token: <...>
Refresh Token: <...>npx express-authx sign-token --id <user-id> --role <role>-
--access-secret <secret> -
--access-expiry <expiry>
npx express-authx sign-token --id=alice --role=moderator --access-secret=mysecret-
--refresh— Verifies using refresh token logic -
--access-secret <secret>— Provide secret manually
npx express-authx verify-token --token <jwt-token>- Access token:
npx express-authx verify-token --token <access-token>- Refresh token:
npx express-authx verify-token --token <your-refresh-token> --refresh💡 If you're using MongoDB blacklisting, always pass the
--mongoflag when verifying a token. Otherwise, the blacklist won’t be checked.
npx express-authx decode-token --token <jwt-token>
npx express-authx decode-token --token <your-token>You’ll get:
{
"id": "user123",
"role": "admin",
"iat": 1751550000,
"exp": 1751553600
}npx express-authx refresh-token --refresh-token <refresh-token>-
--access-secret <secret> -
--refresh-secret <secret> -
--access-expiry <expiry> -
--refresh-expiry <expiry>
Purpose: Invalidate an access token by blacklisting it in MongoDB. Once blacklisted, the token will be rejected on all protected routes.
npx express-authx logout-token --token <token> --mongo <mongo-uri>
npx express-authx verify-token --token <token> --mongo mongodb://localhost:27017Purpose: Starts a small Express server that signs an access token and sets it as an HTTP-only cookie.
npx express-authx set-cookie-token --id <user-id> --role <user-role> [options]-
--id <id>— User ID to embed in the token -
--role <role>— User role to embed in the token
-
--access-secret <secret>— Secret key for signing the access token (default: process.env.ACCESS_SECRET or 'default-access') -
--access-expiry <expiry>— Access token expiry duration (default: '15m') -
--port <port>— Port for the test server (default: 4000)
npx express-authx --helpSee contributing.md for ways to get started.