CORS, Helmet, CSRF & Compression
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:
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.
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.