Cross-Origin Headers, Configured
@fastify/cors
Configure cross-origin access for your API — allow specific origins, methods, headers, and credentials, or open it wide for public consumers.
What you'll learn
- Install @fastify/cors
- Pass origin as a list or function
- Allow credentials for cookie-based auth
CORS controls which other origins can talk to your API from a browser. Without it, browsers refuse cross-origin XHR / fetch. @fastify/cors handles preflight and actual requests in one plugin.
Install & Register
npm install @fastify/cors import cors from '@fastify/cors'
await app.register(cors, {
origin: ['https://app.example.com', 'https://admin.example.com'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
}) Dynamic Origin
For multi-tenant apps, you may need to compute the allowed origin per request.
await app.register(cors, {
origin: (origin, cb) => {
if (!origin) return cb(null, true)
const allowed = /\.example\.com$/.test(new URL(origin).hostname)
cb(null, allowed)
},
credentials: true,
}) Returning true reflects the request origin back. Never combine a wildcard * with credentials: true — browsers reject that.
Development Mode
In local development the simplest config is origin: true, which reflects any origin.
await app.register(cors, {
origin: app.config.NODE_ENV === 'development' ? true : ['https://app.example.com'],
credentials: true,
}) Always gate permissive settings behind an environment check — it is the single most common security regression.
@fastify/rate-limit →