{"name":"cors","description":"Node.js CORS middleware","version":"2.8.6","author":{"name":"Troy Goode","email":"troygoode@gmail.com","url":"https://github.com/troygoode/"},"license":"MIT","keywords":["cors","express","connect","middleware"],"repository":{"type":"git","url":"git+https://github.com/expressjs/cors.git"},"funding":{"type":"opencollective","url":"https://opencollective.com/express"},"main":"./lib/index.js","dependencies":{"object-assign":"^4","vary":"^1"},"devDependencies":{"after":"0.8.2","eslint":"7.30.0","express":"4.21.2","mocha":"9.2.2","nyc":"15.1.0","supertest":"6.1.3"},"engines":{"node":">= 0.10"},"scripts":{"test":"npm run lint && npm run test-ci","test-ci":"nyc --reporter=lcov --reporter=text mocha --require test/support/env","lint":"eslint lib test"},"_id":"cors@2.8.6","gitHead":"f00a8c1f0af727ffe5ed35f3b2d0b1a7eb4b65bb","bugs":{"url":"https://github.com/expressjs/cors/issues"},"homepage":"https://github.com/expressjs/cors#readme","_nodeVersion":"22.10.0","_npmVersion":"10.9.0","dist":{"integrity":"sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==","shasum":"ff5dd69bd95e547503820d29aba4f8faf8dfec96","tarball":"http://registry-npm.ywwl.com/cors/download/cors-2.8.6.tgz","fileCount":4,"unpackedSize":19956,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDl+q2CIKuuULO+TRBoAAt6aAfdQwD4yjeMzyHjKJQTcgIhAK56UWRtdMh6Q0oH6038TOHqqRnJM5u5DcBUj1L6rDsp"}],"size":6456,"noattachment":false,"key":"/cors/-/cors-2.8.6.tgz"},"_npmUser":{"name":"ulisesgascon","email":"ulisesgascondev@gmail.com"},"directories":{},"maintainers":[{"name":"dougwilson","email":"doug@somethingdoug.com"},{"name":"ulisesgascon","email":"ulisesgascondev@gmail.com"},{"name":"troygoode","email":"troygoode@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/cors_2.8.6_1769092890088_0.15137495042247529"},"_hasShrinkwrap":false,"readme":"# cors\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Build Status][github-actions-ci-image]][github-actions-ci-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nCORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.\n\n> [!IMPORTANT]\n> **How CORS Works:** This package sets response headers—it doesn't block requests. CORS is enforced by browsers: they check the headers and decide if JavaScript can read the response. Non-browser clients (curl, Postman, other servers) ignore CORS entirely. See the [MDN CORS guide](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) for details.\n\n* [Installation](#installation)\n* [Usage](#usage)\n  * [Simple Usage](#simple-usage-enable-all-cors-requests)\n  * [Enable CORS for a Single Route](#enable-cors-for-a-single-route)\n  * [Configuring CORS](#configuring-cors)\n  * [Configuring CORS w/ Dynamic Origin](#configuring-cors-w-dynamic-origin)\n  * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)\n  * [Customizing CORS Settings Dynamically per Request](#customizing-cors-settings-dynamically-per-request)\n* [Configuration Options](#configuration-options)\n* [Common Misconceptions](#common-misconceptions)\n* [License](#license)\n* [Original Author](#original-author)\n\n## Installation\n\nThis is a [Node.js](https://nodejs.org/en/) module available through the\n[npm registry](https://www.npmjs.com/). Installation is done using the\n[`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally):\n\n```sh\n$ npm install cors\n```\n\n## Usage\n\n### Simple Usage (Enable *All* CORS Requests)\n\n```javascript\nvar express = require('express')\nvar cors = require('cors')\nvar app = express()\n\n// Adds headers: Access-Control-Allow-Origin: *\napp.use(cors())\n\napp.get('/products/:id', function (req, res, next) {\n  res.json({msg: 'Hello'})\n})\n\napp.listen(80, function () {\n  console.log('web server listening on port 80')\n})\n```\n\n### Enable CORS for a Single Route\n\n```javascript\nvar express = require('express')\nvar cors = require('cors')\nvar app = express()\n\n// Adds headers: Access-Control-Allow-Origin: *\napp.get('/products/:id', cors(), function (req, res, next) {\n  res.json({msg: 'Hello'})\n})\n\napp.listen(80, function () {\n  console.log('web server listening on port 80')\n})\n```\n\n### Configuring CORS\n\nSee the [configuration options](#configuration-options) for details.\n\n```javascript\nvar express = require('express')\nvar cors = require('cors')\nvar app = express()\n\nvar corsOptions = {\n  origin: 'http://example.com',\n  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204\n}\n\n// Adds headers: Access-Control-Allow-Origin: http://example.com, Vary: Origin\napp.get('/products/:id', cors(corsOptions), function (req, res, next) {\n  res.json({msg: 'Hello'})\n})\n\napp.listen(80, function () {\n  console.log('web server listening on port 80')\n})\n```\n\n### Configuring CORS w/ Dynamic Origin\n\nThis module supports validating the origin dynamically using a function provided\nto the `origin` option. This function will be passed a string that is the origin\n(or `undefined` if the request has no origin), and a `callback` with the signature\n`callback(error, origin)`.\n\nThe `origin` argument to the callback can be any value allowed for the `origin`\noption of the middleware, except a function. See the\n[configuration options](#configuration-options) section for more information on all\nthe possible value types.\n\nThis function is designed to allow the dynamic loading of allowed origin(s) from\na backing datasource, like a database.\n\n```javascript\nvar express = require('express')\nvar cors = require('cors')\nvar app = express()\n\nvar corsOptions = {\n  origin: function (origin, callback) {\n    // db.loadOrigins is an example call to load\n    // a list of origins from a backing database\n    db.loadOrigins(function (error, origins) {\n      callback(error, origins)\n    })\n  }\n}\n\n// Adds headers: Access-Control-Allow-Origin: <matched origin>, Vary: Origin\napp.get('/products/:id', cors(corsOptions), function (req, res, next) {\n  res.json({msg: 'Hello'})\n})\n\napp.listen(80, function () {\n  console.log('web server listening on port 80')\n})\n```\n\n### Enabling CORS Pre-Flight\n\nCertain CORS requests are considered 'complex' and require an initial\n`OPTIONS` request (called the \"pre-flight request\"). An example of a\n'complex' CORS request is one that uses an HTTP verb other than\nGET/HEAD/POST (such as DELETE) or that uses custom headers. To enable\npre-flighting, you must add a new OPTIONS handler for the route you want\nto support:\n\n```javascript\nvar express = require('express')\nvar cors = require('cors')\nvar app = express()\n\napp.options('/products/:id', cors()) // preflight for DELETE\napp.del('/products/:id', cors(), function (req, res, next) {\n  res.json({msg: 'Hello'})\n})\n\napp.listen(80, function () {\n  console.log('web server listening on port 80')\n})\n```\n\nYou can also enable pre-flight across-the-board like so:\n\n```javascript\napp.options('*', cors()) // include before other routes\n```\n\nNOTE: When using this middleware as an application level middleware (for\nexample, `app.use(cors())`), pre-flight requests are already handled for all\nroutes.\n\n### Customizing CORS Settings Dynamically per Request\n\nFor APIs that require different CORS configurations for specific routes or requests, you can dynamically generate CORS options based on the incoming request. The `cors` middleware allows you to achieve this by passing a function instead of static options. This function is called for each incoming request and must use the callback pattern to return the appropriate CORS options.\n\nThe function accepts:\n1. **`req`**: \n   - The incoming request object.\n\n2. **`callback(error, corsOptions)`**: \n   - A function used to return the computed CORS options.\n   - **Arguments**:\n     - **`error`**: Pass `null` if there’s no error, or an error object to indicate a failure.\n     - **`corsOptions`**: An object specifying the CORS policy for the current request.\n\nHere’s an example that handles both public routes and restricted, credential-sensitive routes:\n\n```javascript\nvar dynamicCorsOptions = function(req, callback) {\n  var corsOptions;\n  if (req.path.startsWith('/auth/connect/')) {\n    // Access-Control-Allow-Origin: http://mydomain.com, Access-Control-Allow-Credentials: true, Vary: Origin\n    corsOptions = {\n      origin: 'http://mydomain.com',\n      credentials: true\n    };\n  } else {\n    // Access-Control-Allow-Origin: *\n    corsOptions = { origin: '*' };\n  }\n  callback(null, corsOptions);\n};\n\napp.use(cors(dynamicCorsOptions));\n\napp.get('/auth/connect/twitter', function (req, res) {\n  res.send('Hello');\n});\n\napp.get('/public', function (req, res) {\n  res.send('Hello');\n});\n\napp.listen(80, function () {\n  console.log('web server listening on port 80')\n})\n```\n\n## Configuration Options\n\n* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values:\n  - `Boolean` - set `origin` to `true` to reflect the [request origin](https://datatracker.ietf.org/doc/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS.\n  - `String` - set `origin` to a specific origin. For example, if you set it to\n    - `\"http://example.com\"` only requests from \"http://example.com\" will be allowed.\n    - `\"*\"` for all domains to be allowed. \n  - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's 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\".\n  - `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\".\n  - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as `callback(err, origin)`, where `origin` is a non-function value of the `origin` option) as the second.\n* `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']`).\n* `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.\n* `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.\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. Set to an integer to pass the header, otherwise it is omitted.\n* `preflightContinue`: Pass the CORS preflight response to the next handler.\n* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`.\n\nThe default configuration is the equivalent of:\n\n```json\n{\n  \"origin\": \"*\",\n  \"methods\": \"GET,HEAD,PUT,PATCH,POST,DELETE\",\n  \"preflightContinue\": false,\n  \"optionsSuccessStatus\": 204\n}\n```\n\n## Common Misconceptions\n\n### \"CORS blocks requests from disallowed origins\"\n\n**No.** Your server receives and processes every request. CORS headers tell the browser whether JavaScript can read the response—not whether the request is allowed.\n\n### \"CORS protects my API from unauthorized access\"\n\n**No.** CORS is not access control. Any HTTP client (curl, Postman, another server) can call your API regardless of CORS settings. Use authentication and authorization to protect your API.\n\n### \"Setting `origin: 'http://example.com'` means only that domain can access my server\"\n\n**No.** It means browsers will only let JavaScript from that origin read responses. The server still responds to all requests.\n\n## License\n\n[MIT License](http://www.opensource.org/licenses/mit-license.php)\n\n## Original Author\n\n[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))\n\n[coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg\n[coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/cors.svg\n[downloads-url]: https://npmjs.com/package/cors\n[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/cors/ci.yml?branch=master&label=ci\n[github-actions-ci-url]: https://github.com/expressjs/cors?query=workflow%3Aci\n[npm-image]: https://img.shields.io/npm/v/cors.svg\n[npm-url]: https://npmjs.com/package/cors\n","publish_time":1769092890223,"_cnpm_publish_time":1769092890223,"dist-tags":{"latest":"2.8.6"}}