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
Enter fullscreen mode
Exit fullscreen mode
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 .…