Express.js Integration
Express is the primary target framework for node-auth. The auth router is Express-compatible out of the box.
▶ Open live demo in StackBlitz
Source: demo/
Register → Login → Refresh flow
Basic Setup
import express from 'express';
import cookieParser from 'cookie-parser';
import { AuthConfigurator } from '@nik2208/node-auth';
import { MyUserStore } from './stores/user-store';
const app = express();
app.use(express.json());
app.use(cookieParser());
const auth = new AuthConfigurator(
{
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET!,
accessTokenExpiresIn: '15m',
refreshTokenExpiresIn: '7d',
},
new MyUserStore()
);
app.use('/auth', auth.router());
// Protected route
app.get('/api/profile', auth.middleware(), (req, res) => {
res.json(req.user);
});
app.listen(3000);
With Rate Limiting
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 });
app.use('/auth', auth.router({ rateLimiter: limiter }));
With All Optional Stores
import { MySessionStore } from './stores/session-store';
import { MyRbacStore } from './stores/rbac-store';
import { MyMetadataStore } from './stores/metadata-store';
app.use('/auth', auth.router({
sessionStore: new MySessionStore(),
rbacStore: new MyRbacStore(),
metadataStore: new MyMetadataStore(),
onRegister: async (data) => userStore.create(data),
}));