NestJS — Enterprise Node.js

CORS, Helmet, CSRF & Compression

18 min Lesson 58 of 80

CORS, Helmet, CSRF & Compression

Security and HTTP hardening are not a single switch. A NestJS application usually combines CORS policy, Helmet headers, CSRF protection for cookie-authenticated browser flows, and careful compression choices.

Core idea

This feature is about controlling how the application is organized and how it behaves at runtime. These are the points a developer should understand before using it in a real project:

  • CORS controls which origins may call the API from browsers; it is not an authentication system.
  • Helmet sets common security headers, but content security policy needs application-specific tuning.
  • CSRF matters when browsers automatically attach credentials such as cookies.
  • Compression reduces payload size but can be offloaded to Nginx, a CDN, or an API gateway in high-traffic systems.
  • Fastify uses different plugins than Express for several of these concerns.

Practical example

The following example shows the idea in a practical NestJS project. The goal is not to memorize the snippet, but to understand where it belongs in the architecture:

const app = await NestFactory.create(AppModule); app.enableCors({ origin: ['https://app.example.com'], credentials: true, methods: ['GET', 'POST', 'PATCH', 'DELETE'], }); app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'"] }, }, })); app.use(compression());
Design note: Treat security middleware as a policy layer. The safest configuration is usually narrow origins, explicit methods, strict cookie attributes, and CSP tested against the actual frontend.

Production checklist

  • Whitelist exact origins instead of using wildcard CORS with credentials.
  • Tune Helmet CSP after checking scripts, styles, fonts, and image sources.
  • Use CSRF tokens for cookie-authenticated unsafe methods.
  • Avoid app-level compression when a reverse proxy already compresses responses.
Rule of thumb: If the feature makes boundaries clearer and tests easier, it is probably the right choice. If it hides dependencies or makes tracing harder, redesign.

Summary

This lesson covers an advanced NestJS area that matters when building enterprise applications. Focus on clear boundaries, testable behavior, and choosing the right tool for the context instead of using every feature everywhere.