Menu

Security: CORS, Helmet, rate limiting — Fastify with TypeScript (part 14/18)
📰

Security: CORS, Helmet, rate limiting — Fastify with TypeScript (part 14/18)

DEV Community: fastify·Antonio Tripodi·9 days ago
#MA0JvDYK
#devtofastify#devto#dev#fastify#security
Long article (1063 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.