Rate Limiting, Security & Performance
Rate Limiting, Security & Performance
A production NestJS application must defend itself against abuse, expose the right HTTP security headers, and be tuned for throughput. This lesson covers four complementary concerns: rate limiting with @nestjs/throttler, HTTP security headers with Helmet, CORS configuration, and performance tuning — including the Fastify adapter, response compression, and payload size limits.
Rate Limiting with @nestjs/throttler
The throttler module blocks clients that make too many requests in a given time window, protecting your API from brute-force attacks and runaway consumers.
Register the module globally and apply the guard:
Override per-route with the @Throttle() decorator, or exempt internal routes with @SkipThrottle():
ThrottlerStorageRedisService from @nestjs/throttler-storage-redis) so all pods share the same counters.
HTTP Security Headers with Helmet
Helmet sets a collection of well-known HTTP response headers that harden your app against common browser-based attacks (XSS, clickjacking, MIME sniffing, etc.).
helmet()'s default Content-Security-Policy may break inline scripts or external CDN assets. Pass an options object to helmet({ contentSecurityPolicy: { directives: { ... } } }) to tailor it, or disable only the CSP rule while keeping the rest.
CORS Configuration
CORS must be enabled for browser clients to call your API from a different origin. NestJS wraps the cors package:
origin: '*' with credentials: true. Browsers reject this combination. Either specify exact origins or use a dynamic validator function that checks against an allow-list and returns the origin or false.
Performance: Fastify Adapter
NestJS defaults to Express. Swapping in the Fastify adapter typically doubles raw throughput because Fastify has a faster HTTP parser and a more efficient routing engine.
app.use(someExpressMiddleware)) does not work with Fastify. Check your middleware list before switching.
Compression & Payload Limits
Enabling gzip compression reduces response sizes significantly for JSON-heavy APIs. Use the compression package (Express) or Fastify's built-in plugin:
Limit incoming request body size to prevent memory exhaustion attacks. With Express, set it when registering body parsers:
Summary
Secure, performant NestJS applications combine @nestjs/throttler for rate limiting (global guard + per-route overrides), Helmet for security headers, CORS configured with an explicit allow-list and credentials: true only when needed, the optional Fastify adapter for higher throughput, compression to shrink responses, and body-size limits to prevent abuse. These are not optional extras — they are baseline requirements for any internet-facing service.