Security: CORS, Helmet, rate limiting — Fastify with TypeScript (part 14/18)
Security: CORS, Helmet, rate limiting Fourteenth chapter of the "Fastify with TypeScript" series. Before going to production, there are a few baseline protections every API should have. Let's cover CORS, Helmet, and ra
Security: CORS, Helmet, rate limiting
Fourteenth chapter of the "Fastify with TypeScript" series. Before going to production, there are a few baseline protections every API should have. Let's cover CORS, Helmet, and rate limiting with the official plugins, bundled into a single security plugin, and check with curl what each of them actually does.
npm install @fastify/cors @fastify/helmet @fastify/rate-limit
Create src/plugins/security.ts:
// src/plugins/security.ts
import fp from 'fastify-plugin';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import createError from '@fastify/error';
const TooManyRequests = createError('RATE_LIMITED', 'Too many requests, retry in %s', 429);
export default fp(async function securityPlugin(fastify) {
await fastify.register(cors, {
origin: fastify.config.CORS_ORIGIN.split(','),
credentials: true,
});
await fastify.register(helmet, {
contentSecurityPolicy: {
directives: { defaultSrc: ["'self'"] },
},
});
await fastify.register(rateLimit, {
max: 100,
timeWindow: '1 minute',
// A typed error, so the 429 has the same shape as every other error
errorResponseBuilder: (request, context) => new TooManyRequests(context.after),
});
}, { name: 'security' });
Register it in src/app.ts, with its import, right after the openapi plugin:
import security from './plugins/security.ts';
app.register(security);
Security headers with Helmet
curl -i localhost:3000/health
The response now carries a dozen headers it didn't have before, among them:
Content-Security-Policy: default-src 'self';base-uri 'self';...
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Referrer-Policy: no-referrer
Each one switches off a class of browser-side attack: X-Content-Type-Options stops the browser from guessing content types, Strict-Transport-Security tells it to use HTTPS only, X-Frame-Options forbids embedding the response in a frame. For a pure JSON API Helmet's defaults are fine; the Content-Security-Policy directive in our configuration matters only if you also serve HTML.
CORS
Browsers refuse to let a page on one origin read responses from another origin unless the server allows it. @fastify/cors answers that question from the CORS_ORIGIN variable in the config (comma-separated), so it changes per environment without touching code.
A request from the allowed origin gets the permission header:
curl -i localhost:3000/health -H 'Origin: http://localhost:5173'
# access-control-allow-origin: http://localhost:5173
# access-control-allow-credentials: true
A request from any other origin gets no access-control-allow-origin header at all, and the browser will block the page from reading the response:
curl -i localhost:3000/health -H 'Origin: https://evil.example'
Two things to keep in mind. CORS is enforced by the browser: curl got its 200 in both cases, so CORS is not a substitute for authentication. And never use origin: true (accept any origin) together with credentials: true in production.
Rate limiting
The plugin counts requests per IP address and answers 429 when an address goes over the limit. Every limited response says how much is left:
curl -i -X POST localhost:3000/api/v1/users -H 'content-type: application/json' -d '{}'
# x-ratelimit-limit: 100
# x-ratelimit-remaining: 99
# x-ratelimit-reset: 60
The login route deserves a stricter limit, because it is where passwords get guessed. Any route can override the global settings through its config. In src/auth/auth.route.ts:
fastify.post('/login', {
schema: { tags: ['auth'], body: LoginBody, response: { 200: LoginResponse } },
// Stricter than the global limit, and only for this route
config: { rateLimit: { max: 5, timeWindow: '1 minute' } },
}, async (request) => {
return { token: await auth.login(request.body) };
});
Try a wrong password six times in a row. The first five answer 401, the sixth:
HTTP/1.1 429 Too Many Requests
x-ratelimit-limit: 5
x-ratelimit-remaining: 0
retry-after: 60
{"statusCode":429,"error":"RATE_LIMITED","message":"Too many requests, retry in 1 minute"}
The errorResponseBuilder in our plugin throws a typed error, so the 429 goes through the error handler of chapter 10 and has the same shape as every other error.
Put the override on the route, not on the whole auth module: GET /auth/me is called by every page of a frontend, and five requests a minute would lock real users out.
Three facts about where the limit applies, all worth knowing before you rely on it:
- It covers the routes registered after the plugin, which is why
securityis registered before the modules./health, declared directly on the root instance inbuildApp(), is not limited. That happens to be what you want for a health check: an orchestrator probing it every few seconds should never be told to slow down. - On a protected route, the limiter runs after the route's own
onRequesthooks, so a request rejected byauthenticateis not counted. Those requests cost the server almost nothing, but don't assume the counter sees them. - The counters live in the memory of the process. With several instances, each one counts on its own; pass a
redisclient to the plugin to share them.
Minimal security checklist
- Always validate input through TypeBox schemas, and declare response schemas (chapter 7)
- Never send internal error details to the client (chapter 10)
- Use parameterized queries, never string-concatenated SQL (chapter 13)
- Hash passwords, and give the same answer in the same time for a wrong email and a wrong password (chapter 12)
- Set
trustProxy: truein the Fastify options if you're behind a load balancer, or rate limiting will see the proxy's IP instead of the client's - Keep the default
bodyLimit(1 MiB) unless a route really needs more, so nobody can post a huge payload - Keep secrets out of the repository: environment variables only (chapter 4)
⬅️ Previous chapter: Database · ➡️ Next chapter: Testing
This article is part of the "Fastify with TypeScript" series — chapter 14 of 18.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.