@zitterorg/glowing-barnacle v6.10.83
@zitterorg/glowing-barnacle
@zitterorg/glowing-barnacle enables the use of CORS in a Fastify application.
Install
npm i @zitterorg/glowing-barnacleCompatibility
| Plugin version | Fastify version |
|---|---|
^8.0.0 | ^4.0.0 |
^7.0.0 | ^3.0.0 |
^3.0.0 | ^2.0.0 |
^1.0.0 | ^1.0.0 |
Please note that if a Fastify version is out of support, then so are the corresponding version(s) of this plugin in the table above. See Fastify's LTS policy for more details.
Usage
Require @zitterorg/glowing-barnacle and register it as any other plugin, it will add an onRequest hook and a wildcard options route.
import Fastify from 'fastify'
import cors from '@zitterorg/glowing-barnacle'
const fastify = Fastify()
await fastify.register(cors, {
// put your options here
})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
await fastify.listen({ port: 3000 })You can use it as is without passing any option or you can configure it as explained below.
Options
origin: Configures the Access-Control-Allow-Origin CORS header. The value of origin could be of different types:Boolean- setorigintotrueto reflect the request origin, or set it tofalseto disable CORS.String- setoriginto a specific origin. For example if you set it to"http://example.com"only requests from "http://example.com" will be allowed. The special*value (default) allows any origin.RegExp- setoriginto a regular expression pattern that will be used to test the request origin. If it is a match, the request origin will be reflected. For example, the pattern/example\.com$/will reflect any request that is coming from an origin ending with "example.com".Array- setoriginto an array of valid origins. Each origin can be aStringor aRegExp. For example["http://example1.com", /\.example2\.com$/]will accept any request from "http://example1.com" or from a subdomain of "example2.com".Function- setoriginto a function implementing some custom logic. The function takes the request origin as the first parameter and a callback as a second (which expects the signatureerr [Error | null], origin), whereoriginis a non-function value of the origin option. Async-await and promises are supported as well. The Fastify instance is bound to function call and you may access viathis. For example:
origin: (origin, cb) => { const hostname = new URL(origin).hostname if(hostname === "localhost"){ // Request from localhost will pass cb(null, true) return } // Generate an error on other origins, disabling access cb(new Error("Not allowed"), false) }methods: Configures the Access-Control-Allow-Methods CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex:['GET', 'PUT', 'POST']).hook: See the sectionCustom Fastify hook name(default:onRequest)allowedHeaders: Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited string (ex:'Content-Type,Authorization') or an array (ex:['Content-Type', 'Authorization']). If not specified, defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header.exposedHeaders: Configures the Access-Control-Expose-Headers CORS header. Expects a comma-delimited string (ex:'Content-Range,X-Content-Range') or an array (ex:['Content-Range', 'X-Content-Range']). If not specified, no custom headers are exposed.credentials: Configures the Access-Control-Allow-Credentials CORS header. Set totrueto 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 asCache-Control: max-age=${cacheControl}, or set to a string to pass the header asCache-Control: ${cacheControl}(fully define the header value), otherwise the header is omitted.preflightContinue: Pass the CORS preflight response to the route handler (default:false).optionsSuccessStatus: Provides a status code to use for successfulOPTIONSrequests, since some legacy browsers (IE11, various SmartTVs) choke on204.preflight: if needed you can entirely disable preflight by passingfalsehere (default:true).strictPreflight: Enforces strict requirement of the CORS preflight request headers (Access-Control-Request-Method and Origin) as defined by the W3C CORS specification (the current fetch living specification does not define server behavior for missing headers). Preflight requests without the required headers will result in 400 errors when set totrue(default:true).hideOptionsRoute: hide options route from the documentation built using @fastify/swagger (default:true).
:warning: DoS attacks
The use of RegExp or a function for the origin parameter might allow an attacker to perform a Denial of Service
attack. Craft those with extreme care.
Configuring CORS Asynchronously
const fastify = require('fastify')()
fastify.register(require('@zitterorg/glowing-barnacle'), (instance) => {
return (req, callback) => {
const corsOptions = {
// This is NOT recommended for production as it enables reflection exploits
origin: true
};
// do not include CORS headers for requests from localhost
if (/^localhost$/m.test(req.headers.origin)) {
corsOptions.origin = false
}
// callback expects two parameters: error and options
callback(null, corsOptions)
}
})
fastify.register(async function (fastify) {
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
})
fastify.listen({ port: 3000 })Custom Fastify hook name
By default, @zitterorg/glowing-barnacle adds a onRequest hook where the validation and header injection are executed. This can be customized by passing hook in the options. Valid values are onRequest, preParsing, preValidation, preHandler, preSerialization, and onSend.
import Fastify from 'fastify'
import cors from '@zitterorg/glowing-barnacle'
const fastify = Fastify()
await fastify.register(cors, {
hook: 'preHandler',
})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
await fastify.listen({ port: 3000 })When configuring CORS asynchronously, an object with delegator key is expected:
const fastify = require('fastify')()
fastify.register(require('@zitterorg/glowing-barnacle'), {
hook: 'preHandler',
delegator: (req, callback) => {
const corsOptions = {
// This is NOT recommended for production as it enables reflection exploits
origin: true
};
// do not include CORS headers for requests from localhost
if (/^localhost$/m.test(req.headers.origin)) {
corsOptions.origin = false
}
// callback expects two parameters: error and options
callback(null, corsOptions)
},
})
fastify.register(async function (fastify) {
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
})
fastify.listen({ port: 3000 })Acknowledgements
The code is a port for Fastify of expressjs/cors.
License
Licensed under MIT.
expressjs/cors license
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago