Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 42 ยท Testing and Production

Security and Hardening

Harden a NestJS API: security headers with helmet, CORS, CSRF, rate limiting, whitelisting DTOs against mass assignment, secrets and dependency hygiene.

A Nest API that works is not yet an API that is safe. Most real-world attacks do not break clever cryptography. They use a missing header, an over-trusting endpoint, a leaked secret or a request body that was accepted without question. Nest gives you the building blocks for each defense, and this lesson shows where each one belongs and what it actually protects against.

The Nest code and configuration here is read-only, because it needs Node, npm and a real framework. The runnable stand-ins are small, honest demonstrations: a real loopback HTTP server that sets security headers and checks CORS by hand, and a validator that whitelists fields so you can watch mass assignment fail.

Defense in layers

Headers helmet tells browsers how to behave.
CORS Which sites may call your API.
Rate limits Slow down brute force and abuse.
Validation Reject what you did not expect.

No single layer is enough. Stack them.

1 / 2

Security headers with helmet

Browsers have many protective features, such as refusing to sniff content types or to put your page in a frame, but you must switch them on with response headers. The helmet package sets a sensible group of these headers in one call. In Nest it is middleware in main.ts:

TypeScript
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(helmet());
  await app.listen(3000);
}

With the Fastify adapter you register @fastify/helmet instead. Among other things, helmet adds headers like X-Content-Type-Options: nosniff (do not guess a file's type), Strict-Transport-Security (use HTTPS from now on) and a Content-Security-Policy, and it removes the X-Powered-By header that announces your framework.

A JSON-only API gains less from some of these than a website that serves HTML, but the cost is near zero and they protect any page that does get served, such as Swagger UI. If you serve the Swagger page or other HTML, the default Content Security Policy may block its inline scripts, so you relax the policy for those routes deliberately instead of turning helmet off.

CORS

Browsers stop a page on https://shop.example from reading responses of https://api.example unless the API opts in. That opt-in is CORS (cross-origin resource sharing). Nest exposes it as:

TypeScript
app.enableCors({
  origin: ['https://shop.example', 'https://admin.example'],
  methods: ['GET', 'POST', 'PATCH', 'DELETE'],
  credentials: true,
});

Keep three facts straight. CORS is enforced by browsers, so it does not stop curl, scripts or other servers: it is not authentication. origin: true or a wildcard reflects any site, which is fine for a public read-only API and dangerous together with cookies. And credentials: true cannot be combined with the wildcard *: you must name the origins.

CORS in production

The snippet above is fine for a demo, but production needs a policy that differs by environment and cannot be bent by a request. Four rules cover most of it.

1. Read the allowed origins from configuration. Local development, staging and production have different front-end addresses. Keep them in an environment variable and parse it once at startup, so a deploy (not a code change) updates the list:

TypeScript
const allowed = (process.env.CORS_ORIGINS ?? '')
  .split(',')
  .map((origin) => origin.trim())
  .filter(Boolean);

app.enableCors({
  origin: (origin, callback) => {
    callback(null, !origin || allowed.includes(origin));
  },
  methods: ['GET', 'POST', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 600,
});

Match exact origins (scheme, host and port), never a substring or a suffix test such as origin.endsWith('example.com'), which also matches evil-example.com. A request with no Origin header comes from a non-browser client (curl, another server) or a same-origin page, which CORS does not govern, so allowing it is normal.

2. Be deliberate about credentials. With credentials: true the browser sends cookies and the response may be read by the allowed site, so the allow-list must name each origin and must not reflect the request's origin blindly. For cookie sessions also set SameSite and Secure on the cookie, as described under CSRF below.

3. Know what a preflight is. For "non-simple" requests (JSON bodies, an Authorization header, PATCH or DELETE), the browser first sends an OPTIONS request asking permission. The server must answer with Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers. maxAge lets the browser cache that answer, which saves a round trip per request. If your API sits behind a gateway or proxy, make sure it passes OPTIONS through (or answers it consistently) and that exactly one layer adds the CORS headers: duplicated Access-Control-Allow-Origin headers make browsers reject the response.

4. Test the policy. You can check CORS without a browser by sending the requests a browser would send and asserting on the headers:

Terminal
curl -i -X OPTIONS https://api.example.com/orders \
  -H "Origin: https://shop.example" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type"

Expect a 204 with Access-Control-Allow-Origin: https://shop.example. Repeat with Origin: https://evil.example and expect no Access-Control-Allow-Origin header. In Nest you can turn this into an end-to-end test with Supertest, which is worth having because a CORS regression is invisible until a real front end breaks.

The stand-in below follows these rules. It reads origins from a configuration string, answers preflights, and tests allowed and blocked origins with real HTTP requests. It is not Nest's CORS implementation, only the same behavior in a few lines.

Node.js An env-driven allow-list and preflight checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The two configured origins get the headers, and every look-alike gets none, so a browser would block the cross-origin call. Notice the Vary: Origin header: without it a shared cache could store one origin's answer and serve it to another.

CSRF

Cross-site request forgery tricks a logged-in user's browser into sending a request that carries their cookies. It matters when authentication rides on cookies. If your API authenticates with an Authorization: Bearer header that your own JavaScript attaches, a foreign site cannot make the browser add it, so classic CSRF does not apply.

If you use cookie sessions:

  • Set the session cookie with SameSite=Lax (or Strict), HttpOnly and Secure.
  • Require a CSRF token on unsafe methods (POST, PUT, PATCH, DELETE), for example the double-submit-cookie pattern with a maintained package. The older csurf package is deprecated, so pick a current one.
  • Never change state on a GET request.

Rate limits

Login endpoints, password resets and expensive searches attract abuse. The @nestjs/throttler package provides a guard that counts requests per client and answers 429 Too Many Requests:

TypeScript
@Module({
  imports: [ThrottlerModule.forRoot([{ ttl: 60_000, limit: 100 }])],
  providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
})
export class AppModule {}

@Controller('auth')
export class AuthController {
  @Throttle({ default: { limit: 5, ttl: 60_000 } }) // stricter for login
  @Post('login')
  login() { /* ... */ }
}

A single process keeps its counters in memory. Behind several instances or a load balancer you need a shared storage, or the limit applies per instance. The mechanics are explained in Caching, Throttling and Scheduling. Also remember to configure the proxy setting (trust proxy) correctly, or every request appears to come from the load balancer's address.

Validation, whitelisting and mass assignment

Mass assignment happens when you copy a request body straight into a database entity. If the client sends {"name": "Mia", "role": "admin"} and your code does Object.assign(user, body), the client just promoted itself. The cure is to accept only the fields you declared. With the validation pipe:

TypeScript
app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,              // strip properties without a decorator
    forbidNonWhitelisted: true,   // or reject the request instead of stripping
    transform: true,
  }),
);

whitelist only keeps properties that have at least one class-validator decorator, so a DTO field with no decorator is silently dropped. Add forbidNonWhitelisted when you prefer a clear 400 over quiet stripping. Separate DTOs for create and update help too: the DTO a client sends should not even contain id, role or isActive.

Validation is not only about types. Bound your inputs: maximum string length, array sizes, page sizes, and the body size limit of the HTTP adapter, so one request cannot exhaust memory. Use parameterized queries or an ORM, never string concatenation, to prevent SQL injection.

Secrets and configuration

  • Keep secrets (database passwords, JWT signing keys, API tokens) out of the repository. Load them from environment variables or a secret manager, using typed configuration validated at startup so the app refuses to boot without them.
  • Never put secrets, stack traces or SQL in error responses. Production responses carry a short message; details go to logs.
  • Never log passwords, tokens or full card numbers. Redact sensitive fields before logging.
  • Hash passwords with a slow, salted algorithm such as argon2 or bcrypt (Authentication with JWT), and rotate keys when someone with access leaves.

Dependency hygiene

A Nest app can have hundreds of transitive packages. Commit your lock file, run npm audit (or your platform's scanner) in CI, update regularly in small steps, and remove packages you no longer use. Prefer widely used, maintained packages, review what a new dependency pulls in, and pin the Node.js version to a supported release line.

Stand-in: headers, CORS and the framework banner

This is not helmet and not Nest's CORS implementation. It is a real HTTP server on the loopback address with a tiny middleware that sets a few well-known headers and decides CORS by looking at the Origin header. It shows what such middleware changes in the response.

Node.js Security headers and a CORS allow-list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The plain server announces its framework and sends no protective headers. The hardened one removes the banner, adds the headers and echoes the origin only for the allow-listed site. For evil.example no Access-Control-Allow-Origin header is sent, so a browser would refuse to let that page read the response. A curl request would still succeed, which is why CORS is not authentication.

Stand-in: whitelisting stops mass assignment

The second demo is a hand-written validator, not class-validator. It compares two ways of creating a user from a request body: copying everything, and keeping only the fields the DTO declares.

Node.js Mass assignment versus a whitelisted DTO

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The naive version produced an admin that is also inactive, because the client wrote both fields. The whitelisted version kept role: "user" from the server-side defaults. The strict mode answers 400 in Nest, listing the offending property, which makes a probing client easy to spot in logs.

A hardening checklist

  1. helmet() enabled; the framework banner removed.
  2. CORS with an explicit origin list.
  3. Global ValidationPipe with whitelist: true, bounded inputs and a body size limit.
  4. Throttling on every route and a stricter limit on login and password reset.
  5. Cookie sessions: HttpOnly, Secure, SameSite, plus CSRF tokens. Token auth: short-lived tokens, never in URLs.
  6. Secrets from the environment, validated at startup, never logged.
  7. Production errors without internals; details in logs only.
  8. Dependencies audited and updated; the lock file committed.
  9. HTTPS terminated in front of the app, with the proxy trusted correctly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client sends {"name":"Mia","role":"admin"} and the server does Object.assign(user, body). What is this vulnerability called?

    Copying client-controlled fields onto an entity lets the client set fields it should not, such as role. Whitelisting a DTO prevents it.
  2. 2. What does ValidationPipe({ whitelist: true }) do to properties that have no validation decorator?

    whitelist removes properties that are not decorated. Add forbidNonWhitelisted: true if you want a 400 instead of silent stripping.
  3. 3. Which statement about CORS is correct?

    CORS is a browser rule about which pages may read responses. Other clients ignore it, so it is never a substitute for authentication.
  4. 4. When is classic CSRF a real concern?

    Browsers attach cookies automatically, even to requests started by another site. A header your own script adds is not attached by a foreign page.
  5. 5. Why does an in-memory rate limiter fail to protect an app running on four instances behind a load balancer?

    Counters stored per process are not shared. Use a shared store such as Redis, or limit at the proxy or edge.

Summary

  • helmet() sets protective response headers and removes the framework banner; relax its CSP only for routes that need it, such as Swagger.
  • CORS is a browser opt-in, not authentication; list origins explicitly and never combine credentials: true with a wildcard.
  • CSRF matters for cookie authentication: use SameSite, HttpOnly, Secure and a token on unsafe methods.
  • Throttle everything, throttle logins harder, and share counters across instances.
  • Whitelist DTOs (whitelist, forbidNonWhitelisted), bound every input, and use parameterized queries to stop mass assignment and injection.
  • Keep secrets out of git and logs, validate configuration at startup, and audit dependencies in CI.

Continue with Deployment and Performance to ship the hardened app.