{"id":13472777,"url":"https://github.com/fastify/fastify-cors","last_synced_at":"2025-04-29T18:48:31.918Z","repository":{"id":32872938,"uuid":"144390060","full_name":"fastify/fastify-cors","owner":"fastify","description":"Fastify CORS","archived":false,"fork":false,"pushed_at":"2025-03-30T21:24:56.000Z","size":301,"stargazers_count":441,"open_issues_count":2,"forks_count":60,"subscribers_count":17,"default_branch":"main","last_synced_at":"2025-04-25T05:05:23.201Z","etag":null,"topics":["cors","cors-headers","fastify","fastify-plugin"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/cors","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2018-08-11T14:04:04.000Z","updated_at":"2025-04-24T14:24:20.000Z","dependencies_parsed_at":"2023-09-24T07:17:17.591Z","dependency_job_id":"60fa03bd-3e1d-4207-b950-b8eb311eddf5","html_url":"https://github.com/fastify/fastify-cors","commit_stats":{"total_commits":238,"total_committers":57,"mean_commits":4.175438596491228,"dds":0.73109243697479,"last_synced_commit":"7635ecd332348a40f224e0a8ea0a7e658b6ce2c6"},"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-cors/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251153373,"owners_count":21544300,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cors","cors-headers","fastify","fastify-plugin"],"created_at":"2024-07-31T16:00:57.910Z","updated_at":"2025-04-29T18:48:31.898Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/cors\n\n[![CI](https://github.com/fastify/fastify-cors/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-cors/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/cors.svg?style=flat)](https://www.npmjs.com/package/@fastify/cors)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\n`@fastify/cors` enables the use of [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) in a Fastify application.\n\n## Install\n```\nnpm i @fastify/cors\n```\n\n### Compatibility\n\n| Plugin version | Fastify version |\n| ---------------|-----------------|\n| `\u003e=10.x`       | `^5.x`          |\n| `\u003e=8.x \u003c10.x`  | `^4.x`          |\n| `^7.x`         | `^3.x`          |\n| `\u003e=3.x \u003c7.x`   | `^2.x`          |\n| `\u003e=1.x \u003c3.x`   | `^1.x`          |\n\n\nPlease note that if a Fastify version is out of support, then so are the corresponding versions of this plugin\nin the table above.\nSee [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.\n\n## Usage\nRequire `@fastify/cors` and register it as any other plugin. It adds an `onRequest` hook and a [wildcard options route](https://github.com/fastify/fastify/issues/326#issuecomment-411360862).\n```js\nimport Fastify from 'fastify'\nimport cors from '@fastify/cors'\n\nconst fastify = Fastify()\nawait fastify.register(cors, {\n  // put your options here\n})\n\nfastify.get('/', (req, reply) =\u003e {\n  reply.send({ hello: 'world' })\n})\n\nawait fastify.listen({ port: 3000 })\n```\nYou can use it as is without passing any option or you can configure it as explained below.\n### Options\n* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. The value of origin can be:\n  - `Boolean`: Set to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), or `false` to disable CORS.\n  - `String`: Set to a specific origin (e.g., `\"http://example.com\"`). The special `*` value (default) allows any origin.\n  - `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`).\n  - `Array`: Set to an array of valid origins, each being a `String` or `RegExp` (e.g., `[\"http://example1.com\", /\\.example2\\.com$/]`).\n  - `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:\n  ```js\n  origin: (origin, cb) =\u003e {\n    const hostname = new URL(origin).hostname\n    if(hostname === \"localhost\"){\n      //  Request from localhost will pass\n      cb(null, true)\n      return\n    }\n    // Generate an error on other origins, disabling access\n    cb(new Error(\"Not allowed\"), false)\n  }\n  ```\n* `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](https://fetch.spec.whatwg.org/#methods) `GET,HEAD,POST`.\n* `hook`: See [Custom Fastify hook name](#custom-fastify-hook-name). Default: `onRequest`.\n* `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.\n* `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.\n* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header; otherwise, it is omitted.\n* `maxAge`: Configures the **Access-Control-Max-Age** CORS header in seconds. Set to an integer to pass the header; otherwise, it is omitted.\n* `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.\n* `preflightContinue`: Passes the CORS preflight response to the route handler. Default: `false`.\n* `optionsSuccessStatus`: Provides a status code for successful `OPTIONS` requests, as some legacy browsers (IE11, various SmartTVs) choke on `204`.\n* `preflight`: Disables preflight by passing `false`. Default: `true`.\n* `strictPreflight`: Enforces strict requirements for the CORS preflight request headers (**Access-Control-Request-Method** and **Origin**) as defined by the [W3C CORS specification](https://www.w3.org/TR/2020/SPSD-cors-20200602/#resource-preflight-requests). Preflight requests without the required headers result in 400 errors when set to `true`. Default: `true`.\n* `hideOptionsRoute`: Hides the options route from documentation built using [@fastify/swagger](https://github.com/fastify/fastify-swagger). Default: `true`.\n\n#### :warning: DoS attacks\n\nUsing `RegExp` or a `function` for the `origin` parameter may enable Denial of Service attacks.\nCraft with extreme care.\n\n### Configuring CORS Asynchronously\n\n```js\nconst fastify = require('fastify')()\n\nfastify.register(require('@fastify/cors'), (instance) =\u003e {\n  return (req, callback) =\u003e {\n    const corsOptions = {\n      // This is NOT recommended for production as it enables reflection exploits\n      origin: true\n    };\n\n    // do not include CORS headers for requests from localhost\n    if (/^localhost$/m.test(req.headers.origin)) {\n      corsOptions.origin = false\n    }\n\n    // callback expects two parameters: error and options\n    callback(null, corsOptions)\n  }\n})\n\nfastify.register(async function (fastify) {\n  fastify.get('/', (req, reply) =\u003e {\n    reply.send({ hello: 'world' })\n  })\n})\n\nfastify.listen({ port: 3000 })\n```\n\n### Disabling CORS for a specific route\n\nCORS can be disabled at the route level by setting the `cors` option to `false`.\n\n```js\nconst fastify = require('fastify')()\n\nfastify.register(require('@fastify/cors'), { origin: '*' })\n\nfastify.get('/cors-enabled', (_req, reply) =\u003e {\n  reply.send('CORS headers')\n})\n\nfastify.get('/cors-disabled', { cors: false }, (_req, reply) =\u003e {\n  reply.send('No CORS headers')\n})\n\nfastify.listen({ port: 3000 })\n```\n\n### Custom Fastify hook name\n\nBy 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`.\n\n```js\nimport Fastify from 'fastify'\nimport cors from '@fastify/cors'\n\nconst fastify = Fastify()\nawait fastify.register(cors, {\n  hook: 'preHandler',\n})\n\nfastify.get('/', (req, reply) =\u003e {\n  reply.send({ hello: 'world' })\n})\n\nawait fastify.listen({ port: 3000 })\n```\n\nTo configure CORS asynchronously, provide an object with the `delegator` key:\n\n```js\nconst fastify = require('fastify')()\n\nfastify.register(require('@fastify/cors'), {\n  hook: 'preHandler',\n  delegator: (req, callback) =\u003e {\n    const corsOptions = {\n      // This is NOT recommended for production as it enables reflection exploits\n      origin: true\n    };\n\n    // do not include CORS headers for requests from localhost\n    if (/^localhost$/m.test(req.headers.origin)) {\n      corsOptions.origin = false\n    }\n\n    // callback expects two parameters: error and options\n    callback(null, corsOptions)\n  },\n})\n\nfastify.register(async function (fastify) {\n  fastify.get('/', (req, reply) =\u003e {\n    reply.send({ hello: 'world' })\n  })\n})\n\nfastify.listen({ port: 3000 })\n```\n\n## Acknowledgments\n\nThe code is a port for Fastify of [`expressjs/cors`](https://github.com/expressjs/cors).\n\n## License\n\nLicensed under [MIT](./LICENSE).\u003cbr/\u003e\n[`expressjs/cors` license](https://github.com/expressjs/cors/blob/master/LICENSE)\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript","Extension"],"sub_categories":["**Node Modules Used**"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-cors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-cors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-cors/lists"}