Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Authentication and Security

Security Headers, CORS and Rate Limiting

Harden a Fastify API: set security headers like Helmet, configure CORS and preflight correctly, and add a rate limiter that answers 429 with Retry-After.

Authentication decides who may call your API. This lesson covers the layer around it: response headers that tell browsers to be strict, CORS rules that decide which websites may call you, and rate limits that slow abusive clients down. In Fastify these are the plugins @fastify/helmet, @fastify/cors and @fastify/rate-limit. They are not installed on this site, so you will build small versions of each with the same behavior and then see the real registration code.

Three cheap defenses

Security headers Tell browsers to be strict.
CORS Choose which sites may call you.
Rate limit Slow down repeated requests.

Plugins exist for all three.

1 / 2

Security headers

A few response headers switch on browser protections. The @fastify/helmet plugin sets a good default group; knowing the main ones helps you read its output:

Header What it does
Strict-Transport-Security Browser must use HTTPS for this host for a period.
X-Content-Type-Options: nosniff Do not guess types: a "text" response is not run as a script.
Content-Security-Policy Whitelists where scripts, images and frames may load from.
X-Frame-Options / frame-ancestors Stops other sites from putting your page in a frame (clickjacking).
Referrer-Policy Limits how much of your URL leaks to other sites.
Cross-Origin-Resource-Policy Controls which origins may embed your resources.

A pure JSON API cares less about CSP, but nosniff, HSTS and a tight Referrer-Policy cost nothing. Add them in one onSend hook (the plugin does the same):

Node.js Security headers in an onSend hook

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.

Because the hook runs for every response, even the 404 error carries the headers. In real Fastify:

JavaScript
import helmet from '@fastify/helmet';
await app.register(helmet, { global: true });   // sane defaults, configurable per directive

CORS in plain words

Browsers enforce the same-origin policy: a page at https://app.example may not read responses from https://api.example unless the API opts in with CORS headers. The API says which origins are welcome in Access-Control-Allow-Origin.

Two kinds of requests exist:

  • Simple requests (a GET, or a POST with a form content type): the browser sends them and then checks the response headers.
  • Preflighted requests (JSON bodies, custom headers like Authorization, methods such as PUT and DELETE): the browser first sends an OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. Only if the answer allows it does the real request follow.
Node.js An allow-list CORS handler with preflight

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 real plugin does all of this, including the Vary header:

JavaScript
import cors from '@fastify/cors';
await app.register(cors, {
  origin: ['https://app.example'],            // never '*' together with credentials
  methods: ['GET', 'POST', 'DELETE'],
  allowedHeaders: ['content-type', 'authorization'],
  credentials: true,                          // allow cookies; requires an exact origin
  maxAge: 600,
});

CORS protects the user's browser, not your server. Anyone can call your API with curl and ignore CORS entirely. Never use it as authentication, and never reflect any Origin back without checking an allow-list.

Rate limiting

A rate limiter counts requests per client in a time window and refuses the extras with 429 Too Many Requests, plus a Retry-After header telling the client how long to wait. It protects login routes from password guessing, expensive endpoints from abuse, and your database from a runaway client.

The simplest algorithm is a fixed window: allow N requests per key per window. The key is usually the client IP (behind a proxy, configure Fastify's trustProxy option so request.ip is the real client, not the proxy) or an API key.

Node.js A fixed-window rate limiter returning 429

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.

In real Fastify, the plugin supports per-route limits and Redis storage so every process shares counters:

JavaScript
import rateLimit from '@fastify/rate-limit';
await app.register(rateLimit, { global: true, max: 100, timeWindow: '1 minute' });

app.post('/login', { config: { rateLimit: { max: 5, timeWindow: '1 minute' } } }, loginHandler);

A fixed window lets a client send 2N requests around a boundary. Sliding windows and token buckets smooth that out. The in-memory version also forgets counters on restart and counts per process, so behind a load balancer use a shared store.

A sensible baseline

  1. Register helmet-style headers globally.
  2. Allow-list your front-end origins in CORS; list methods and headers explicitly.
  3. Rate limit globally at a generous level and lower on login, password reset and signup.
  4. Set trustProxy correctly, otherwise every client appears to come from your proxy and shares one limit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the X-Content-Type-Options: nosniff header do?

    With nosniff, a response labelled as data is not treated as a script just because it looks like one.
  2. 2. A curl command ignores your CORS configuration. Why?

    CORS is a browser rule that protects users. It does not authenticate or restrict other clients.
  3. 3. When does a browser send a preflight OPTIONS request?

    Non-simple requests are preceded by a preflight so the server can approve the method and headers first.
  4. 4. Which response pair tells a client it is rate limited and when to return?

    429 Too Many Requests with Retry-After is the standard way to ask a client to slow down.

Summary

  • Security headers (nosniff, HSTS, a tight Referrer-Policy, CSP where it fits) are one hook or one @fastify/helmet registration.
  • CORS is an allow-list for browsers: echo only known origins, answer preflight, set Vary: Origin, and never treat it as authentication.
  • Rate limiters count per key and window, answer 429 with Retry-After, and need a shared store when you run several processes.
  • Configure trustProxy so IP-based limits use the real client address.

Next: Authorization, Input Hardening and Secrets