UNPKG

@bodheesh/create-bodhi-node-app

Version:

Create a production-ready Node.js REST API with zero configuration

40 lines (33 loc) 980 B
import { Request, Response, NextFunction } from 'express'; import rateLimit from 'express-rate-limit'; import helmet from 'helmet'; import xss from 'xss-clean'; import csrf from 'csurf'; export const generateSecurityMiddleware = (app: any) => { // Basic security headers app.use(helmet()); // XSS Protection app.use(xss()); // Rate limiting const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); app.use('/api', limiter); // CSRF Protection app.use(csrf({ cookie: true })); // CSRF Token middleware app.use((req: Request, res: Response, next: NextFunction) => { res.locals.csrfToken = req.csrfToken(); next(); }); // Error handler app.use((err: any, req: Request, res: Response, next: NextFunction) => { if (err.code === 'EBADCSRFTOKEN') { return res.status(403).json({ error: 'Invalid CSRF token' }); } next(err); }); };