@fastify/cors
Official Fastify plugin that adds configurable CORS headers and preflight handling to any Fastify API.
Repository Health
Technical Analysis
@fastify/cors enables Cross-Origin Resource Sharing (CORS) support in Fastify applications with a single plugin registration. It handles the Access-Control-Allow-Origin, -Methods, -Headers, -Credentials, and -Max-Age headers, plus the OPTIONS preflight route Fastify needs to satisfy browser CORS checks, all without requiring you to write header logic by hand.
Maintained by the core Fastify organization, the plugin supports static origins, wildcard, regular expressions, arrays, and both callback- and promise-based dynamic origin resolution, along with per-route overrides via route config. It is built on fastify-plugin so it correctly decorates the parent Fastify instance rather than creating an encapsulated context, and ships first-class TypeScript types.
What You Get
- Automatic Access-Control-Allow-Origin, -Methods, -Headers, -Credentials, -Expose-Headers, and -Max-Age header management
- A pre-wired OPTIONS
*preflight route with strict-preflight validation and configurable success status code - Static, wildcard, RegExp, array, and async/callback-based dynamic origin resolution
- Per-route CORS overrides and disabling via
config.corson individual routes - Configurable lifecycle hook (onRequest, preHandler, onSend, etc.) so CORS headers are applied at the point that fits your app
- Correct Vary header management (cached via toad-cache) so CDNs and browsers don’t serve cross-origin responses to the wrong client
Common Use Cases
- Allowing a separately hosted frontend (SPA, mobile web client) to call a Fastify API on a different origin
- Restricting API access to a known allowlist of origins using a string array or RegExp
- Building multi-tenant APIs where the allowed origin must be resolved dynamically per request (e.g. from a database of tenant domains)
- Exposing custom response headers to browser JavaScript via Access-Control-Expose-Headers
- Enabling credentialed (cookie-based) cross-origin requests with Access-Control-Allow-Credentials
Under The Hood
Architecture — The plugin is a single fp()-wrapped Fastify plugin (index.js) that, on registration, normalizes options (merging user options over defaultOptions), validates the configured lifecycle hook against a fixed allowlist, and attaches one hook function (handleCors) that runs on every request. That handler resolves the effective origin value (static, array, RegExp, or async/callback function via resolveOriginWrapper), writes the CORS response headers (addCorsHeaders), and — for OPTIONS requests when preflight is enabled — writes preflight-specific headers (addPreflightHeaders) and short-circuits the response unless preflightContinue is set. A wildcard fastify.options('*', ...) route is registered alongside the hook specifically so preflight responses can be sent before authentication or other plugins run, using a corsPreflightEnabled request decorator as the flag between the hook and the route handler. vary.js is a small, self-contained module implementing RFC 7230-compliant Vary header composition backed by a bounded toad-cache FIFO cache to avoid re-parsing repeated header values. Tech Stack — Plain CommonJS JavaScript (type: commonjs) targeting Fastify 5.x (declared via the fp() metadata { fastify: '5.x' }), with only two runtime dependencies: fastify-plugin (for correct instance-level, non-encapsulated registration) and toad-cache (LRU/FIFO caching for Vary header values). Dev tooling is modern: neostandard for linting via ESLint 9 flat config, c8 for coverage with a --100 threshold enforced in CI, and tstyche for compile-time TypeScript type-testing against the shipped .d.ts file. Code Quality — The test suite (test/cors.test.js, hooks.test.js, preflight.test.js, vary.test.js) totals roughly 2,700 lines across 4 files using Node’s built-in node:test runner and Fastify’s inject() for header-level assertions, and package.json enforces 100% coverage via c8 --100; there are no lingering TODOs or dead code paths in index.js, and error paths (invalid hook, invalid origin, malformed preflight) are handled explicitly rather than silently swallowed. API Design — Registration is a single fastify.register(cors, options) call with sane defaults (open origin, GET/HEAD/POST, onRequest hook) that work out of the box, while every commonly needed variation — static list, RegExp, async lookup, per-route override, alternate lifecycle hook — is reachable through the same options object without needing a second API surface, and the shipped TypeScript definitions give autocomplete on every option.
Used by 13 apps in this directory
Activepieces
Automation · AI Assistants
Open-source AI automation platform that converts 280+ workflow integrations into MCP servers for LLMs, with no-code builders and TypeScript extensibility.
Colanode
Knowledge Management · Team Chat · Collaboration
Local-first, self-hosted workspace that combines real-time chat, Notion-style pages, and structured databases — all synced via CRDTs so you work offline without losing a keystroke.
Dittofeed
Marketing · Automation
Open-source omni-channel customer engagement platform for automating transactional and marketing messages via email, SMS, WhatsApp, Slack, and mobile push.
GraphQL Hive
Developer Tools · Devops · Monitoring
Open-source GraphQL schema registry and observability platform with breaking change detection, federation support, and CI/CD integration for teams of any size.
Infisical
Security · Devops
The open-source platform for secrets, certificates, privileged access, and AI agent security — all in one self-hostable system.
Logseq
Note Taking · Knowledge Management
A privacy-first, open-source knowledge graph platform combining Markdown, Org-mode, bidirectional linking, and local-first storage for building your second brain.
OpenPanel
Analytics
Open-source Mixpanel alternative with session replay, MCP integration, and privacy-first product analytics you fully control.
optio
AI Agents · AI Code Assistants
Self-hosted AI agent workflow orchestration that runs on your Kubernetes cluster — from ticket intake to squash-merged PR, entirely within your infrastructure.
Palmr.
File Storage · Security
Self-hosted, privacy-focused file sharing without limits