### Full CORS Configuration Example Source: https://context7.com/expressjs/cors/llms.txt Demonstrates all available configuration options for the CORS middleware, including origin, methods, headers, credentials, and caching. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', // Allowed origin (string, boolean, RegExp, array, or function) methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // Allowed HTTP methods allowedHeaders: ['Content-Type', 'Authorization'], // Allowed request headers exposedHeaders: ['X-Total-Count'], // Headers exposed to browser credentials: true, // Allow credentials (cookies, auth headers) maxAge: 3600, // Preflight cache duration in seconds preflightContinue: false, // Pass preflight to next handler optionsSuccessStatus: 204 // Status for successful OPTIONS (legacy browser support: use 200) } app.use(cors(corsOptions)) app.get('/api/users', function (req, res) { res.setHeader('X-Total-Count', '42') res.json([{ id: 1, name: 'John' }]) }) app.listen(3000, function () { console.log('Fully configured CORS server running on port 3000') }) ``` -------------------------------- ### Install CORS Middleware Source: https://context7.com/expressjs/cors/llms.txt Install the cors package using npm. This is the first step before using it in your Express application. ```bash npm install cors ``` -------------------------------- ### Dynamic Origin Validation with Callback Source: https://context7.com/expressjs/cors/llms.txt Use a callback function for the 'origin' option to dynamically validate origins, for example, by loading allowed origins from a database. It allows requests with no origin. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: function (origin, callback) { // Example: Load allowed origins from database var allowedOrigins = ['http://example.com', 'http://localhost:3000'] // Allow requests with no origin (like mobile apps or curl) if (!origin) return callback(null, true) if (allowedOrigins.indexOf(origin) !== -1) { callback(null, true) } else { callback(new Error('Not allowed by CORS')) } } } app.use(cors(corsOptions)) app.get('/api/data', function (req, res) { res.json({ data: 'dynamically validated origin' }) }) app.listen(3000) ``` -------------------------------- ### Configure with Regular Expression Source: https://context7.com/expressjs/cors/llms.txt Use a RegExp in the 'origin' option to dynamically match multiple origins based on a pattern, such as allowing any subdomain of a specific domain. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { // Allow any subdomain of example.com origin: /\.example\.com$/ } app.use(cors(corsOptions)) app.get('/api/data', function (req, res) { // Requests from api.example.com, app.example.com, etc. are allowed res.json({ data: 'accessible to example.com subdomains' }) }) app.listen(3000) ``` -------------------------------- ### Dynamic CORS Options Per Request Source: https://context7.com/expressjs/cors/llms.txt Implement dynamic CORS configurations by providing a delegate function to `cors()`. This function receives the request and a callback to set options based on request properties like path. ```javascript var express = require('express') var cors = require('cors') var app = express() var dynamicCorsOptions = function (req, callback) { var corsOptions if (req.path.startsWith('/auth/connect/')) { // Restricted routes: specific origin with credentials corsOptions = { origin: 'http://mydomain.com', credentials: true } } else if (req.path.startsWith('/api/public/')) { // Public API: allow all origins corsOptions = { origin: '*' } } else { // Default: specific allowed origins corsOptions = { origin: ['http://example.com', 'http://localhost:3000'] } } callback(null, corsOptions) } app.use(cors(dynamicCorsOptions)) app.get('/auth/connect/twitter', function (req, res) { res.send('Twitter OAuth - restricted CORS') }) app.get('/api/public/data', function (req, res) { res.json({ public: true }) }) app.get('/api/data', function (req, res) { res.json({ data: 'default CORS policy' }) }) app.listen(3000) ``` -------------------------------- ### Enable CORS Pre-Flight for Specific Routes Source: https://github.com/expressjs/cors/blob/master/README.md Use `app.options()` with `cors()` to enable pre-flight requests for specific routes that use non-GET/HEAD/POST HTTP verbs or custom headers. This handler should be defined before the route handler. ```javascript var express = require('express') var cors = require('cors') var app = express() app.options('/products/:id', cors()) // preflight for DELETE app.delete('/products/:id', cors(), function (req, res, next) { res.json({msg: 'Hello'}) }) app.listen(80, function () { console.log('web server listening on port 80') }) ``` -------------------------------- ### Configure with Array of Origins Source: https://context7.com/expressjs/cors/llms.txt Allow multiple specific origins by providing an array to the 'origin' option, which can include strings and RegExp patterns for flexible origin control. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: [ 'http://localhost:3000', 'http://example1.com', /\.example2\.com$/ // any subdomain of example2.com ] } app.use(cors(corsOptions)) app.get('/api/data', function (req, res) { res.json({ data: 'accessible to whitelisted origins' }) }) app.listen(3000) ``` -------------------------------- ### Configure Allowed HTTP Methods Source: https://context7.com/expressjs/cors/llms.txt Specify allowed HTTP methods for cross-origin requests using the `methods` option. This can be an array of strings or a comma-separated string. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', methods: ['GET', 'POST', 'PUT'], // Only allow specific methods // Can also be a string: methods: 'GET,POST,PUT' } app.use(cors(corsOptions)) app.put('/api/resource', function (req, res) { res.json({ updated: true }) }) app.listen(3000) ``` -------------------------------- ### Default CORS Configuration Source: https://context7.com/expressjs/cors/llms.txt Shows the default configuration used by the CORS middleware when no options are specified. This is equivalent to using `app.use(cors())`. ```javascript // Default configuration equivalent var defaultOptions = { origin: '*', // Allow all origins methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // All standard methods preflightContinue: false, // Handle OPTIONS internally optionsSuccessStatus: 204 // No Content response for preflight } // These two are equivalent: app.use(cors()) app.use(cors(defaultOptions)) ``` -------------------------------- ### Enable CORS Pre-Flight Globally Source: https://github.com/expressjs/cors/blob/master/README.md To enable pre-flight requests for all routes, use `app.options('*', cors())`. Ensure this is placed before other route definitions. ```javascript app.options('*', cors()) // include before other routes ``` -------------------------------- ### Enable Preflight for Specific Routes Source: https://context7.com/expressjs/cors/llms.txt Handle preflight OPTIONS requests explicitly for routes requiring complex CORS handling. Use `app.options('/route', cors())` before the actual route handler. ```javascript var express = require('express') var cors = require('cors') var app = express() // Enable preflight for DELETE requests on this route app.options('/products/:id', cors()) app.delete('/products/:id', cors(), function (req, res, next) { res.json({ msg: 'Product deleted' }) }) // Enable preflight for all routes app.options('*', cors()) app.listen(3000) ``` -------------------------------- ### Configure Allowed Headers Source: https://context7.com/expressjs/cors/llms.txt Define which headers are permitted in actual cross-origin requests using the `allowedHeaders` option. Accepts an array or a comma-separated string. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'] // Can also be a string: allowedHeaders: 'Content-Type,Authorization' } app.use(cors(corsOptions)) app.post('/api/data', function (req, res) { res.json({ received: true }) }) app.listen(3000) ``` -------------------------------- ### Pass Preflight to Next Handler Source: https://context7.com/expressjs/cors/llms.txt Use `preflightContinue: true` to allow the preflight OPTIONS request to proceed to the next middleware instead of being handled immediately by the CORS middleware. `optionsSuccessStatus` can be set for successful OPTIONS responses. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', preflightContinue: true, // Don't short-circuit OPTIONS requests optionsSuccessStatus: 204 } app.use(cors(corsOptions)) // Custom OPTIONS handler app.options('/api/custom', function (req, res) { // Add custom preflight logic here res.setHeader('X-Custom-Preflight', 'handled') res.status(204).end() }) app.listen(3000) ``` -------------------------------- ### Configure Max Age for Preflight Cache Source: https://context7.com/expressjs/cors/llms.txt Set the `maxAge` option to control how long preflight OPTIONS request results are cached by the browser, specified in seconds. A value of 86400 seconds caches for 24 hours. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', maxAge: 86400 // Cache preflight response for 24 hours (in seconds) } app.use(cors(corsOptions)) app.delete('/api/resource/:id', function (req, res) { res.json({ deleted: req.params.id }) }) app.listen(3000) ``` -------------------------------- ### Enable All CORS Requests Source: https://github.com/expressjs/cors/blob/master/README.md Use the cors middleware with default settings to allow all cross-origin requests. This is the simplest way to enable CORS. ```javascript var express = require('express') var cors = require('cors') var app = express() // Adds headers: Access-Control-Allow-Origin: * app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({msg: 'Hello'}) }) app.listen(80, function () { console.log('web server listening on port 80') }) ``` -------------------------------- ### Configure Exposed Headers Source: https://context7.com/expressjs/cors/llms.txt Use `exposedHeaders` to specify which response headers the browser can access. This is useful for custom headers or pagination information. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', exposedHeaders: ['Content-Range', 'X-Content-Range', 'X-Total-Count'] } app.use(cors(corsOptions)) app.get('/api/items', function (req, res) { res.setHeader('X-Total-Count', '100') res.json({ items: [] }) }) app.listen(3000) ``` -------------------------------- ### Reflect Request Origin with Credentials Source: https://context7.com/expressjs/cors/llms.txt Set 'origin: true' to reflect the request's origin in the Access-Control-Allow-Origin header, allowing any origin while also enabling credentials. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: true, // Reflects the requesting origin credentials: true } app.use(cors(corsOptions)) app.get('/api/user', function (req, res) { // Access-Control-Allow-Origin will echo the request origin // Access-Control-Allow-Credentials: true res.json({ user: 'authenticated user data' }) }) app.listen(3000) ``` -------------------------------- ### Enable All CORS Requests Source: https://context7.com/expressjs/cors/llms.txt Enable CORS for all routes by applying the cors() middleware globally. This sets the Access-Control-Allow-Origin header to '*'. ```javascript var express = require('express') var cors = require('cors') var app = express() // Enable CORS for all routes - sets Access-Control-Allow-Origin: * app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({ msg: 'This response is available to all origins' }) }) app.listen(3000, function () { console.log('CORS-enabled server listening on port 3000') }) ``` -------------------------------- ### Enable Credentials in CORS Source: https://context7.com/expressjs/cors/llms.txt Set `credentials: true` in CORS options to allow cookies and HTTP authentication headers in cross-origin requests. Ensure your `origin` is not set to '*'. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', credentials: true // Sets Access-Control-Allow-Credentials: true } app.use(cors(corsOptions)) app.get('/api/session', function (req, res) { // Cookies will be included in cross-origin requests res.json({ session: req.cookies }) }) app.listen(3000) ``` -------------------------------- ### Disable CORS Headers Source: https://context7.com/expressjs/cors/llms.txt Demonstrates how to disable CORS headers entirely by setting `origin: false`. The middleware remains in place but does not add any `Access-Control-*` headers to the response. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: false // No CORS headers will be set } app.use(cors(corsOptions)) app.get('/internal', function (req, res) { // No Access-Control-* headers in response res.json({ internal: 'data' }) }) app.listen(3000) ``` -------------------------------- ### Dynamically Customize CORS Settings Source: https://github.com/expressjs/cors/blob/master/README.md Pass a function to the `cors()` middleware to dynamically set CORS options based on the incoming request. This function receives the request object and a callback to return CORS options. ```javascript var dynamicCorsOptions = function(req, callback) { var corsOptions; if (req.path.startsWith('/auth/connect/')) { // Access-Control-Allow-Origin: http://mydomain.com, Access-Control-Allow-Credentials: true, Vary: Origin corsOptions = { origin: 'http://mydomain.com', credentials: true }; } else { // Access-Control-Allow-Origin: * corsOptions = { origin: '*' }; } callback(null, corsOptions); }; app.use(cors(dynamicCorsOptions)); app.get('/auth/connect/twitter', function (req, res) { res.send('Hello'); }); app.get('/public', function (req, res) { res.send('Hello'); }); app.listen(80, function () { console.log('web server listening on port 80') }) ``` -------------------------------- ### Enable CORS for a Single Route Source: https://context7.com/expressjs/cors/llms.txt Apply CORS middleware to specific routes by passing cors() as route middleware. Other routes will not have CORS headers enabled. ```javascript var express = require('express') var cors = require('cors') var app = express() // CORS only on this specific route app.get('/products/:id', cors(), function (req, res, next) { res.json({ msg: 'CORS enabled only for this route' }) }) // This route has no CORS headers app.get('/internal', function (req, res, next) { res.json({ msg: 'No CORS headers here' }) }) app.listen(3000) ``` -------------------------------- ### Default CORS Configuration Source: https://github.com/expressjs/cors/blob/master/README.md This JSON object represents the default configuration for the CORS middleware when no specific options are provided. ```json { "origin": "*", "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", "preflightContinue": false, "optionsSuccessStatus": 204 } ``` -------------------------------- ### Configure CORS with Dynamic Origin Validation Source: https://github.com/expressjs/cors/blob/master/README.md Use a function to dynamically validate origins based on external data, such as a database. This allows for flexible and dynamic CORS policies. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: function (origin, callback) { // db.loadOrigins is an example call to load // a list of origins from a backing database db.loadOrigins(function (error, origins) { callback(error, origins) }) } } // Adds headers: Access-Control-Allow-Origin: , Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({msg: 'Hello'}) }) app.listen(80, function () { console.log('web server listening on port 80') }) ``` -------------------------------- ### Configure Specific Origin Source: https://context7.com/expressjs/cors/llms.txt Restrict CORS to a specific origin by providing an options object with the 'origin' property set to the desired domain. This also sets the Vary: Origin header. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', optionsSuccessStatus: 200 // some legacy browsers (IE11, SmartTVs) choke on 204 } // Sets Access-Control-Allow-Origin: http://example.com, Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'Only http://example.com can read this response' }) }) app.listen(3000) ``` -------------------------------- ### Configure CORS with Specific Origin Source: https://github.com/expressjs/cors/blob/master/README.md Configure the cors middleware to allow requests only from a specific origin. This enhances security by restricting access. ```javascript var express = require('express') var cors = require('cors') var app = express() var corsOptions = { origin: 'http://example.com', optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 } // Adds headers: Access-Control-Allow-Origin: http://example.com, Vary: Origin app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({msg: 'Hello'}) }) app.listen(80, function () { console.log('web server listening on port 80') }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.