Software Crafting

Securing Node.js APIs in Production: Implementing Advanced Rate Limiting, Helmet, and Redis

DDeepak RajputBackend Development8 min read10 Apr 2026Updated 2026-11-07
A translucent wireframe shield on a dark grid floor with bundles of red light lines streaming through it

TL;DR: A default Express app sends an X-Powered-By header, has no rate limiting, and leaves input validation to you. This guide hardens a Node.js API with Helmet headers suited to JSON responses, Redis-backed rate limiting with express-rate-limit, rate-limit-redis and ioredis so limits hold across horizontally scaled instances, tighter body size limits, schema validation against NoSQL operator injection, and a strict CORS allowlist.

Key Takeaways

  • helmet() already removes X-Powered-By and sets X-Content-Type-Options: nosniff; for a JSON API, tighten it with X-Frame-Options: DENY and a default-src 'none'; frame-ancestors 'none' Content Security Policy.
  • The default in-memory store of express-rate-limit keeps a separate count in every process and resets on restart, so it does not enforce a shared limit across PM2 or Kubernetes replicas.
  • Use rate-limit-redis with an ioredis client so every instance shares the same counters (for example, 100 requests per 15-minute window per IP).
  • Add a much stricter limiter to login, password reset and OTP routes, and set trust proxy correctly so limits apply to client IPs rather than your load balancer.
  • Validate request bodies with a schema library such as Zod so objects like {"$ne": null} never reach a MongoDB query. express-mongo-sanitize and hpp modify req.query, which Express 5 no longer allows.

Express is designed to be minimal, so security hardening is left to the application. Out of the box, Express advertises itself with an X-Powered-By: Express header, applies no rate limits, and passes whatever JSON a client sends straight into your route handlers. Nothing stops a script from calling your /login endpoint thousands of times an hour.

None of these is a problem on a laptop. In production, they let an automated client guess passwords, inject query operators into your database calls, or tie up CPU parsing large request bodies. Rate limits that live in each process's memory also stop working as intended once you run more than one instance.

This guide builds a layered defense: HTTP header hardening, distributed rate limiting backed by Redis, payload size limits, schema validation, and a CORS allowlist. The examples use Express 5, Helmet 8, express-rate-limit 8, rate-limit-redis 6 and ioredis.

HTTP Header Hardening: Why You Need Helmet

By default, Express includes an X-Powered-By: Express header in every response. Removing it offers limited security benefit (Helmet's own documentation says so), but it does make simple fingerprinting slightly harder. The more useful headers are the ones Express does not send at all: protection against MIME sniffing, framing (clickjacking) and, for any HTML you serve, a Content Security Policy.

Helmet is a collection of middleware functions that set these HTTP headers. app.use(helmet()) already applies sensible defaults, including X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, X-XSS-Protection: 0 (which turns off the old browser XSS filter, because that filter caused its own vulnerabilities) and removal of X-Powered-By. For an API that only returns JSON you can be stricter than the defaults:

// server.js
const express = require('express');
const helmet = require('helmet');

const app = express();

// Express's own switch; Helmet also removes the header
app.disable('x-powered-by');

app.use(
  helmet({
    // A JSON API never needs to load scripts, styles or frames,
    // so replace Helmet's HTML-oriented default policy with "allow nothing".
    contentSecurityPolicy: {
      useDefaults: false,
      directives: {
        defaultSrc: ["'none'"],
        frameAncestors: ["'none'"],
      },
    },
    // Legacy equivalent of frame-ancestors 'none' for older browsers
    xFrameOptions: { action: 'deny' },
  }),
);

app.get('/api/health', (req, res) => res.status(200).json({ status: 'ok' }));

Production Note: Helmet 7 and later use header-based option names such as xFrameOptions, xPoweredBy and xContentTypeOptions. Older tutorials use frameguard, hidePoweredBy, noSniff and xssFilter. If the same server also renders HTML pages, give those routes a real CSP (with script-src listing your own origin and any hostnames you load scripts from) instead of the 'none' policy above.

The default-src 'none'; frame-ancestors 'none' policy and X-Frame-Options: DENY match the response headers the OWASP REST Security Cheat Sheet recommends for API responses.

The Trap of In-Memory Rate Limiting (And the Redis Solution)

Many developers discover the express-rate-limit package and drop it into their codebase. Out of the box, it stores request counts per IP address in the memory of the Node.js process.

That works for a single process. Behind a load balancer with PM2 cluster mode or several Kubernetes pods, each process keeps its own counter. With four instances, a client can make up to four times the intended number of requests, and every deploy or pod restart resets the counts to zero.

The fix is a shared store. Redis is a common choice because it keeps counters in memory, supports atomic increments with expiry, and is already present in many stacks. If you are designing this kind of shared infrastructure for a larger API, our backend development and API services cover rate limiting and API hardening.

Here is how you wire express-rate-limit to a Redis store using ioredis. The sendCommand signature follows the rate-limit-redis README for ioredis:

// rateLimiter.js
const { rateLimit } = require('express-rate-limit');
const { RedisStore } = require('rate-limit-redis');
const Redis = require('ioredis');

// Connect to your Redis instance
const redisClient = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');

redisClient.on('error', (err) => console.error('Redis Client Error', err));

const globalLimiter = rateLimit({
  // 15 minutes
  windowMs: 15 * 60 * 1000,

  // Allow each IP 100 requests per window
  limit: 100,

  // Send the standard RateLimit headers and drop the legacy X-RateLimit-* ones
  standardHeaders: 'draft-8',
  legacyHeaders: false,

  // Share counters across every instance through Redis.
  // Each limiter needs its own RedisStore instance and prefix.
  store: new RedisStore({
    sendCommand: (command, ...args) => redisClient.call(command, ...args),
    prefix: 'global_rl:',
  }),

  message: {
    status: 429,
    error: 'Too many requests from this IP. Please try again after 15 minutes.',
  },
});

module.exports = { globalLimiter, redisClient };

Decide what should happen when Redis is unavailable. By default express-rate-limit blocks requests if the store errors (passOnStoreError: false). Setting it to true keeps the API up during a Redis outage at the cost of no rate limiting for that period.

Warning: If your Node.js application sits behind a reverse proxy (like Nginx, an AWS ALB, or Cloudflare), req.ip is the proxy's address, so every user shares one rate limit bucket. Set app.set('trust proxy', 1) (the number of proxies in front of the app) before your limiters so Express reads the client IP from X-Forwarded-For. Do not set it to true unless you control every hop, because clients can then spoof that header. express-rate-limit logs a validation error when it detects either misconfiguration.

Throttling Specific Vulnerable Endpoints

A global limit of 100 requests per 15 minutes is reasonable for general API traffic. It is far too generous for sensitive endpoints like /login, /forgot-password, or /verify-otp, where it would still allow 100 password guesses every 15 minutes.

To slow down brute-force and credential-stuffing attacks, add stricter limiters to those routes:

// authLimiter.js
const { rateLimit } = require('express-rate-limit');
const { RedisStore } = require('rate-limit-redis');
const { redisClient } = require('./rateLimiter');

// Strict limiter for authentication routes
const authLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  limit: 5, // 5 failed attempts per IP per hour
  standardHeaders: 'draft-8',
  legacyHeaders: false,
  // Don't count responses with status < 400 (successful logins)
  skipSuccessfulRequests: true,
  store: new RedisStore({
    sendCommand: (command, ...args) => redisClient.call(command, ...args),
    prefix: 'auth_rl:',
  }),
  message: {
    status: 429,
    error: 'Too many failed login attempts. Please try again after an hour.',
  },
});

module.exports = { authLimiter };

// App usage
// app.use('/api/', globalLimiter);
// app.post('/api/auth/login', authLimiter, loginController);

With skipSuccessfulRequests: true, only responses with a status code of 400 or above count toward the limit, so users who log in successfully are not penalized. Make sure your login handler returns a 4xx status for failed attempts. Per-IP limits are coarse: many users can share one IP behind an office network or mobile carrier NAT, and attackers can rotate IPs. Combine this limiter with per-account protections such as progressive delays and alerts on repeated failures.

Defending Against NoSQL Injection

If you use MongoDB, your API can be vulnerable to NoSQL operator injection. SQL injection smuggles code into a query string; NoSQL injection exploits the fact that express.json() turns the request body into JavaScript objects, which can contain MongoDB query operators.

Consider a login route that expects {"email": "[email protected]", "password": "password123"}. An attacker sends: {"email": "[email protected]", "password": {"$ne": null}}

If you pass those values straight into a query like User.findOne({ email: req.body.email, password: req.body.password }), the filter matches the admin user whose password is "not equal to null", and the check is bypassed. (Real code should store password hashes and compare them with a function such as bcrypt.compare, but the same operator trick works on any field you filter by.)

The most reliable defense is to validate the shape and type of every input before it reaches your database code. Here is the login body validated with Zod 4:

// loginValidation.js
const express = require('express');
const { z } = require('zod');

const app = express();
app.use(express.json({ limit: '10kb' }));

const loginSchema = z.object({
  email: z.email(),
  password: z.string().min(1).max(200),
});

app.post('/login', async (req, res) => {
  const parsed = loginSchema.safeParse(req.body);
  if (!parsed.success) {
    // {"$ne": null} is an object, not a string, so it is rejected here
    return res.status(400).json({ error: 'Invalid login payload' });
  }

  const { email, password } = parsed.data;
  // Look up the user by email, then compare the password hash
  // ...
  res.status(204).end();
});

As a second layer, Mongoose can neutralize operators in query filters. With mongoose.set('sanitizeFilter', true), Mongoose wraps any nested object whose keys start with $ in $eq, so { password: { $ne: null } } is treated as a literal value instead of an operator.

Older guides recommend the express-mongo-sanitize middleware for this. It works by rewriting req.query, which is a read-only getter in Express 5, and its issue tracker has open reports of it failing with "Cannot set property query". If you are on Express 5, rely on schema validation and sanitizeFilter instead.

Restricting Payload Sizes to Protect the Event Loop

Node.js runs your JavaScript on a single thread. Parsing a large JSON body with JSON.parse blocks that thread, so other requests on the same process wait until parsing finishes. Large or deeply nested payloads are therefore a cheap way to degrade a Node.js service.

Express's built-in parsers already cap bodies at 100kb by default. Most APIs can go lower, and you should not raise the limit globally just because one route needs to accept large uploads.

// payloadLimits.js
const express = require('express');

const app = express();

// Limit JSON bodies to 10kb (the default is 100kb).
// Larger bodies are rejected with 413 Payload Too Large.
app.use(express.json({ limit: '10kb' }));

// Same for URL-encoded form submissions
app.use(express.urlencoded({ extended: false, limit: '10kb' }));

// For a route that genuinely needs large bodies, use a separate parser
// (or stream uploads straight to object storage) instead of raising the global limit.

HTTP parameter pollution is the query-string version of the same problem: GET /api/users?sort=asc&sort=desc produces req.query.sort === ['asc', 'desc'], and code that expects a string can crash. The hpp middleware addressed this by rewriting req.query, which no longer works in Express 5. Validate query parameters with the same schema approach as request bodies, for example z.enum(['asc', 'desc']) for sort.

Taming CORS for Cross-Origin Safety

Cross-Origin Resource Sharing (CORS) is often misunderstood. To get past preflight errors, developers frequently use app.use(cors()), which sends Access-Control-Allow-Origin: *.

With *, any website's JavaScript can read your API's responses to requests that do not carry credentials. Browsers refuse to combine * with credentialed requests, so the more dangerous mistake is reflecting any Origin back while also setting credentials: true: that lets any site make authenticated calls with your users' cookies and read the results. Note that CORS controls who can read responses; it is not a CSRF defense. Cookie-based APIs still need SameSite cookies or CSRF tokens.

Define an explicit allowlist of origins:

// corsSetup.js
const express = require('express');
const cors = require('cors');

const app = express();

// Allowed origins per environment
const allowedOrigins =
  process.env.NODE_ENV === 'production'
    ? ['https://myproductionapp.com', 'https://admin.myproductionapp.com']
    : ['http://localhost:3000', 'http://127.0.0.1:5173'];

const corsOptions = {
  origin(origin, callback) {
    // Requests without an Origin header (curl, server-to-server, native apps)
    // are not subject to CORS; authenticate them like any other request.
    if (!origin) return callback(null, true);

    // false omits the CORS headers, so the browser blocks the response
    callback(null, allowedOrigins.includes(origin));
  },
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  credentials: true, // Only if you send cookies across origins
};

app.use(cors(corsOptions));

Passing an Error to the callback, as many examples do, turns a disallowed origin into a 500 response in your logs. Returning false is quieter and has the same effect in the browser.

Summary: A Layered Defense

No single package secures a Node.js API. Each layer covers a different class of problem:

  1. Traffic: Redis-backed rate limiting so limits hold across every instance, with stricter limits on authentication routes.
  2. HTTP: Helmet headers for a JSON API and an explicit CORS allowlist.
  3. Request parsing: small body size limits to keep large payloads from tying up the event loop.
  4. Data: schema validation with Zod, plus Mongoose sanitizeFilter if you use MongoDB, to keep query operators out of your database calls.

Together, these address the most common automated attacks against a public Express API. They do not replace authentication, authorization checks on every route, dependency updates, or upstream DDoS protection from your CDN or load balancer.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

Why is the default Express.js configuration not enough for production?

Express is deliberately minimal. It sends an X-Powered-By header, sets no security headers, applies no rate limits, and does not validate request bodies. Those are left to middleware such as Helmet, express-rate-limit and a schema validation library.

Why shouldn't I use in-memory rate limiting for my Node.js API?

With PM2 cluster mode or several Kubernetes pods, each process keeps its own in-memory counter, so a client can exceed your intended limit by spreading requests across instances. Restarting or redeploying a process also resets its counts to zero.

How does Redis solve rate-limiting issues in distributed systems?

Redis gives all your Node.js instances one shared set of counters with atomic increments and expiry, so a request counts toward the same limit no matter which instance handles it. Decide in advance whether the API should block or allow traffic if Redis becomes unavailable.

What is Helmet and why do I need it for my API?

Helmet is a collection of Express middleware functions that set security-related HTTP headers. Its defaults remove X-Powered-By, stop MIME sniffing, restrict framing to prevent clickjacking, and set a Content Security Policy.

Do I need a Content Security Policy (CSP) in Helmet if my API only serves JSON?

Most CSP directives only affect HTML documents, but a short policy is still worthwhile. OWASP recommends default-src 'none' and frame-ancestors 'none' for API responses, which costs nothing and limits the damage if a response is ever opened directly in a browser.

Does express-mongo-sanitize work with Express 5?

Not reliably. It rewrites req.query, which is a read-only getter in Express 5, and its issue tracker has open reports of errors. Validate inputs with a schema library and enable Mongoose's sanitizeFilter option instead.

About the author

Deepak Rajput

Founder and CEO of SoftwareCrafting

Deepak Rajput is the Founder and CEO of SoftwareCrafting in Delhi and writes about web, mobile, backend, cloud, security, and engineering leadership.

Writes about Next.js, Node.js, React Native, PostgreSQL, AWS, Kubernetes.

View author profile

Last updated: 2026-11-07