All Projects → fastify → fastify-cors

fastify / fastify-cors

Licence: MIT license
Fastify CORS

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to fastify-cors

create-fastify-app
An utility that help you to generate or add plugin to your Fastify project
Stars: ✭ 53 (-75%)
Mutual labels:  cors, fastify, fastify-plugin
fastify-env
Fastify plugin to check environment variables
Stars: ✭ 129 (-39.15%)
Mutual labels:  fastify, fastify-plugin
fastify-awilix
Dependency injection support for fastify
Stars: ✭ 52 (-75.47%)
Mutual labels:  fastify, fastify-plugin
fastify-passport
Use passport strategies for authentication within a fastify application
Stars: ✭ 150 (-29.25%)
Mutual labels:  fastify, fastify-plugin
fastify-postgres
Fastify PostgreSQL connection plugin
Stars: ✭ 144 (-32.08%)
Mutual labels:  fastify, fastify-plugin
fastify-vue
A nuxt.js fastify plugin
Stars: ✭ 27 (-87.26%)
Mutual labels:  fastify, fastify-plugin
fastify-axios
Add axios http client to your fastify instance
Stars: ✭ 28 (-86.79%)
Mutual labels:  fastify, fastify-plugin
fastify-autoroutes
fastest way to map directories to URLs in fastify
Stars: ✭ 70 (-66.98%)
Mutual labels:  fastify, fastify-plugin
fastify-etag
Automatically generate etags for HTTP responses, for Fastify
Stars: ✭ 61 (-71.23%)
Mutual labels:  fastify, fastify-plugin
fastify-caching
A Fastify plugin to facilitate working with cache headers
Stars: ✭ 123 (-41.98%)
Mutual labels:  fastify, fastify-plugin
session
Session plugin for fastify
Stars: ✭ 52 (-75.47%)
Mutual labels:  fastify, fastify-plugin
fastify-leveldb
Plugin to share a common LevelDB connection across Fastify.
Stars: ✭ 19 (-91.04%)
Mutual labels:  fastify, fastify-plugin
fastify-accepts
Add accepts parser to fastify
Stars: ✭ 51 (-75.94%)
Mutual labels:  fastify, fastify-plugin
fastify-loader
The route loader for the cool kids!
Stars: ✭ 17 (-91.98%)
Mutual labels:  fastify, fastify-plugin
fastify-cron
Run cron jobs alongside your Fastify server 👷
Stars: ✭ 32 (-84.91%)
Mutual labels:  fastify, fastify-plugin
fastify-hasura
A Fastify plugin to have fun with Hasura.
Stars: ✭ 30 (-85.85%)
Mutual labels:  fastify, fastify-plugin
fastify-openapi-glue
A plugin for Fastify to autogenerate a configuration based on a OpenApi(v2/v3) specification.
Stars: ✭ 94 (-55.66%)
Mutual labels:  fastify, fastify-plugin
fastify-file-upload
Fastify plugin for uploading files
Stars: ✭ 68 (-67.92%)
Mutual labels:  fastify, fastify-plugin
fastify-vite
This plugin lets you load a Vite client application and set it up for Server-Side Rendering (SSR) with Fastify.
Stars: ✭ 497 (+134.43%)
Mutual labels:  fastify, fastify-plugin
fastify-csrf
A fastify csrf plugin.
Stars: ✭ 88 (-58.49%)
Mutual labels:  fastify, fastify-plugin

@fastify/cors

CI NPM version js-standard-style

@fastify/cors enables the use of CORS in a Fastify application.

Supports Fastify versions 3.x. Please refer to this branch and related versions for Fastify ^2.x compatibility. Please refer to this tag and related versions for Fastify ^1.x compatibility.

Install

npm i @fastify/cors

Usage

Require @fastify/cors and register it as any other plugin, it will add a preHandler hook and a wildcard options route.

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), { 
  // put your options here
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(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 - set origin to true to reflect the request origin, or set it to false to disable CORS.
    • String - set origin to 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 - set origin to 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 - set origin to an array of valid origins. Each origin can be a String or a RegExp. For example ["http://example1.com", /\.example2\.com$/] will accept any request from "http://example1.com" or from a subdomain of "example2.com".
    • Function - set origin to 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 signature err [Error | null], origin), where origin is 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 via this. 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"))
    }
  • 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']).
  • 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 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.
  • preflightContinue: Pass the CORS preflight response to the route handler (default: false).
  • optionsSuccessStatus: Provides a status code to use for successful OPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204.
  • preflight: if needed you can entirely disable preflight by passing false here (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 to true (default: true).
  • hideOptionsRoute: hide options route from the documentation built using @fastify/swagger (default: true).

Configuring CORS Asynchronously

const fastify = require('fastify')()

fastify.register(require('@fastify/cors'), function (instance) {

  return (req, callback) => {
    let corsOptions;
    const origin = req.headers.origin
    // do not include CORS headers for requests from localhost
    const hostname = new URL(origin).hostname
    if(hostname === "localhost"){
      corsOptions = { origin: false }
    } else {
      corsOptions = { origin: true }
    }
    callback(null, corsOptions) // callback expects two parameters: error and options
  }
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(3000)

Acknowledgements

The code is a port for Fastify of expressjs/cors.

License

Licensed under MIT.
expressjs/cors license

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].