Back to Node.js & Express
Advanced
30 min Read

Production Security

Learning Objectives

  • JWT Implementation
  • Rate Limiting
  • CORS & Helmet

Production Security: Hardening your API

Shipping an API without security headers and rate limiting is asking for trouble. Here’s the "Senior Dev" checklist for securing Express apps.

1. Helmet: Secure Headers

Helmet sets various HTTP headers to help protect your app from common vulnerabilities like XSS and Clickjacking.

javascript code
const helmet = require('helmet');
app.use(helmet());

2. Rate Limiting

Prevent Brute Force and DoS attacks by limiting the number of requests from a single IP.

javascript code
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // limit each IP to 100 requests per window
    message: 'Too many requests from this IP, please try again later'
});

app.use('/api/', limiter);

3. JWT Best Practices

JSON Web Tokens (JWT) should be used for stateless authentication, but you must do it right:

  • Short Expiry: Access tokens should expire in 15-30 mins.
  • Refresh Tokens: Store these in HttpOnly cookies to prevent XSS.
  • Secret Rotation: Use environment variables and rotate secrets periodically.

4. NoSQL/SQL Injection

Never trust user input. Use parameterized queries (SQL) or Mongoose-level validation (NoSQL). Avoid eval() at all costs.

javascript code
// BAD
const user = await User.find({ email: req.body.email }); // vulnerable if email is an object

// GOOD
app.use(mongoSanitize()); // middleware to clean req.body/params

Dependency Scanning

Use npm audit or tools like Snyk to scan your node_modules for known vulnerabilities regularly.

Confused about this chapter?

Ask our DevVault AI Assistant for instant clarification!

Ask DevVault AI