@fastify/cors
CORS plugin for Fastify — configure cross-origin resource sharing with full support for preflight requests and dynamic origins.
@fastify/cors
FastifyCORS plugin for Fastify — configure cross-origin resource sharing with full support for preflight requests and dynamic origins.
Fit
Bundle (gzip)
4.0 kB
15.1 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Browser security blocks cross-origin requests. Configuring CORS headers in Fastify manually requires handling OPTIONS preflight responses across all routes, managing allowed origin lists, and setting correct Access-Control-* headers.
What It Does
@fastify/cors registers a plugin that intercepts all requests and adds the appropriate CORS headers. It supports static and dynamic origin configuration (function-based for per-request decisions), credentials, exposed headers, and max age for preflight caching.
Installation
npm install @fastify/corsUsage Example
import fastify from 'fastify';
import cors from '@fastify/cors';
const app = fastify();
await app.register(cors, {
origin: (origin, cb) => {
const allowed = ['https://myapp.com', 'https://staging.myapp.com'];
cb(null, allowed.includes(origin ?? ''));
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
});Related packages
Auto-load Fastify plugins from a directory — organize routes and plugins as files and let the framework discover them automatically.
@fastify/cookieFastifyPlugin for Fastify that adds support for reading and setting cookies, including signed cookies.
@fastify/helmetFastifySecurity headers plugin for Fastify — sets HTTP headers that protect against common web vulnerabilities like XSS, clickjacking, and MIME sniffing.
@fastify/jwtFastifyJWT authentication plugin for Fastify — sign, verify, and decode tokens with a decorator-based API that integrates with Fastify's request lifecycle.
@fastify/multipartFastifyMultipart form data / file upload plugin for Fastify — stream files directly to storage without buffering in memory.