Smart CORS headers middleware for your Express.js applications.
$ npm install @starefossen/express-cors --save
const cors = require('@starefossen/express-cors');
The simple configuration is controlled by environment variables:
Variable | Description | Default |
---|---|---|
CORS_ALLOW_CREDENTIALS |
allow-credentials (boolean) | undefined |
CORS_ALLOW_HEADERS |
allow-headers header (comma separated string) | Content-Type |
CORS_ALLOW_METHODS |
allow-methods header (comma separated string) | GET, OPTIONS |
CORS_ALLOW_ORIGINS |
orins whitelist (comma seperated string) | "" |
CORS_DENY_ORIGINS |
origins blacklist (comma seperated string) | "" |
CORS_EXPOSE_HEADERS |
expose-headers header (comma seperated string) | "" |
CORS_MAX_AGE |
max-age header (integer) | 0 |
CORS_REQUIRE_ORIGIN |
require origin header from client (boolean) | false |
const cors = require('@starefossen/express-cors');
app.use(cors.middleware);
The advanced configuration takes in a configuration object. All values defaults to their environment conunterpart as statated in the simple configuration.
const cors = require('@starefossen/express-cors');
app.use(cors({
allowCredentials: false,
allowHeaders: 'Content-Type',
allowMethods: 'GET, OPTIONS',
allowOrigins: 'foo.com,bar.com',
denyOrigins: 'example.com',
exposeHeaders: 'x-request-time',
maxAge: 133734,
requireOrigin: true,
});
If you want to allow local development domains like localhost
or file://
you
can add the following to your CORS_ALLOW_ORIGINS
environment variable:
CORS_ALLOW_ORIGINS='localhost,null'