Gathering detailed insights and metrics for @fastify/cors
Gathering detailed insights and metrics for @fastify/cors
Gathering detailed insights and metrics for @fastify/cors
Gathering detailed insights and metrics for @fastify/cors
npm install @fastify/cors
Typescript
Module System
Node Version
NPM Version
99.5
Supply Chain
100
Quality
87.4
Maintenance
100
Vulnerability
99.6
License
JavaScript (89.68%)
TypeScript (10.32%)
Total Downloads
88,314,268
Last Day
48,628
Last Week
1,092,367
Last Month
4,637,872
Last Year
43,481,065
NOASSERTION License
461 Stars
300 Commits
64 Forks
17 Watchers
3 Branches
60 Contributors
Updated on Jul 16, 2025
Latest Version
11.0.1
Package Id
@fastify/cors@11.0.1
Unpacked Size
112.43 kB
Size
16.21 kB
File Count
20
NPM Version
10.8.2
Node Version
20.18.1
Published on
Mar 25, 2025
Cumulative downloads
Total Downloads
Last Day
5.3%
48,628
Compared to previous day
Last Week
-2.3%
1,092,367
Compared to previous week
Last Month
4%
4,637,872
Compared to previous month
Last Year
41.8%
43,481,065
Compared to previous year
2
@fastify/cors
enables the use of CORS in a Fastify application.
npm i @fastify/cors
Plugin version | Fastify version |
---|---|
^10.x | ^5.x |
^8.x | ^4.x |
^7.x | ^3.x |
^3.x | ^2.x |
^1.x | ^1.x |
Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.
Require @fastify/cors
and register it as any other plugin. It adds an onRequest
hook and a wildcard options route.
1import Fastify from 'fastify' 2import cors from '@fastify/cors' 3 4const fastify = Fastify() 5await fastify.register(cors, { 6 // put your options here 7}) 8 9fastify.get('/', (req, reply) => { 10 reply.send({ hello: 'world' }) 11}) 12 13await fastify.listen({ port: 3000 })
You can use it as is without passing any option or you can configure it as explained below.
origin
: Configures the Access-Control-Allow-Origin CORS header. The value of origin can be:
Boolean
: Set to true
to reflect the request origin, or false
to disable CORS.String
: Set to a specific origin (e.g., "http://example.com"
). The special *
value (default) allows any origin.RegExp
: Set to a regular expression pattern to test the request origin. If it matches, the request origin is reflected (e.g., /example\.com$/
returns the origin only if it ends with example.com
).Array
: Set to an array of valid origins, each being a String
or RegExp
(e.g., ["http://example1.com", /\.example2\.com$/]
).Function
: Set to a function with custom logic. The function takes the request origin as the first parameter and a callback as the second (signature err [Error | null], origin
). Async-await and promises are supported. The Fastify instance is bound to the function call and can be accessed via this
. For example:1origin: (origin, cb) => { 2 const hostname = new URL(origin).hostname 3 if(hostname === "localhost"){ 4 // Request from localhost will pass 5 cb(null, true) 6 return 7 } 8 // Generate an error on other origins, disabling access 9 cb(new Error("Not allowed"), false) 10}
methods
: Configures the Access-Control-Allow-Methods CORS header. Expects a comma-delimited string (e.g., 'GET,HEAD,POST') or an array (e.g., ['GET', 'HEAD', 'POST']
). Default: CORS-safelisted methods GET,HEAD,POST
.hook
: See Custom Fastify hook name. Default: onRequest
.allowedHeaders
: Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited string (e.g., 'Content-Type,Authorization'
) or an array (e.g., ['Content-Type', 'Authorization']
). Defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header if not specified.exposedHeaders
: Configures the Access-Control-Expose-Headers CORS header. Expects a comma-delimited string (e.g., 'Content-Range,X-Content-Range'
) or an array (e.g., ['Content-Range', 'X-Content-Range']
). No custom headers are exposed if not specified.credentials
: Configures the Access-Control-Allow-Credentials CORS header. Set to true
to pass the header; otherwise, it is omitted.maxAge
: Configures the Access-Control-Max-Age CORS header in seconds. Set to an integer to pass the header; otherwise, it is omitted.cacheControl
: Configures the Cache-Control header for CORS preflight responses. Set to an integer to pass the header as Cache-Control: max-age=${cacheControl}
, or set to a string to pass the header as Cache-Control: ${cacheControl}
. Otherwise, the header is omitted.preflightContinue
: Passes the CORS preflight response to the route handler. Default: false
.optionsSuccessStatus
: Provides a status code for successful OPTIONS
requests, as some legacy browsers (IE11, various SmartTVs) choke on 204
.preflight
: Disables preflight by passing false
. Default: true
.strictPreflight
: Enforces strict requirements for the CORS preflight request headers (Access-Control-Request-Method and Origin) as defined by the W3C CORS specification. Preflight requests without the required headers result in 400 errors when set to true
. Default: true
.hideOptionsRoute
: Hides the options route from documentation built using @fastify/swagger. Default: true
.Using RegExp
or a function
for the origin
parameter may enable Denial of Service attacks.
Craft with extreme care.
1const fastify = require('fastify')() 2 3fastify.register(require('@fastify/cors'), (instance) => { 4 return (req, callback) => { 5 const corsOptions = { 6 // This is NOT recommended for production as it enables reflection exploits 7 origin: true 8 }; 9 10 // do not include CORS headers for requests from localhost 11 if (/^localhost$/m.test(req.headers.origin)) { 12 corsOptions.origin = false 13 } 14 15 // callback expects two parameters: error and options 16 callback(null, corsOptions) 17 } 18}) 19 20fastify.register(async function (fastify) { 21 fastify.get('/', (req, reply) => { 22 reply.send({ hello: 'world' }) 23 }) 24}) 25 26fastify.listen({ port: 3000 })
CORS can be disabled at the route level by setting the cors
option to false
.
1const fastify = require('fastify')() 2 3fastify.register(require('@fastify/cors'), { origin: '*' }) 4 5fastify.get('/cors-enabled', (_req, reply) => { 6 reply.send('CORS headers') 7}) 8 9fastify.get('/cors-disabled', { cors: false }, (_req, reply) => { 10 reply.send('No CORS headers') 11}) 12 13fastify.listen({ port: 3000 })
By default, @fastify/cors
adds an onRequest
hook for validation and header injection. This can be customized by passing hook
in the options. Valid values are onRequest
, preParsing
, preValidation
, preHandler
, preSerialization
, and onSend
.
1import Fastify from 'fastify' 2import cors from '@fastify/cors' 3 4const fastify = Fastify() 5await fastify.register(cors, { 6 hook: 'preHandler', 7}) 8 9fastify.get('/', (req, reply) => { 10 reply.send({ hello: 'world' }) 11}) 12 13await fastify.listen({ port: 3000 })
To configure CORS asynchronously, provide an object with the delegator
key:
1const fastify = require('fastify')() 2 3fastify.register(require('@fastify/cors'), { 4 hook: 'preHandler', 5 delegator: (req, callback) => { 6 const corsOptions = { 7 // This is NOT recommended for production as it enables reflection exploits 8 origin: true 9 }; 10 11 // do not include CORS headers for requests from localhost 12 if (/^localhost$/m.test(req.headers.origin)) { 13 corsOptions.origin = false 14 } 15 16 // callback expects two parameters: error and options 17 callback(null, corsOptions) 18 }, 19}) 20 21fastify.register(async function (fastify) { 22 fastify.get('/', (req, reply) => { 23 reply.send({ hello: 'world' }) 24 }) 25}) 26 27fastify.listen({ port: 3000 })
The code is a port for Fastify of expressjs/cors
.
Licensed under MIT.
expressjs/cors
license
No vulnerabilities found.
fastify-cors
`fastify-cors@6.1.0` has been deprecated. Please use `@fastify/cors@7.0.0` instead.
http-proxy-middleware
The one-liner node.js proxy middleware for connect, express, next.js and more
@forrestjs/service-fastify-cors
ForrestJS service which adds CORS management capabilities to a Fastify server.
@types/fastify-cors
Stub TypeScript definitions entry for fastify-cors, which provides its own types definitions