Corser
Corser is a highly configurable middleware for Node.js designed to handle Cross-Origin Resource Sharing (CORS). It offers a flexible approach to managing CORS preflight requests and setting appropriate response headers, supporting both static whitelists for allowed origins and dynamic origin checking through a callback function. The package's current stable version is 2.0.1, released in August 2016. Due to the lack of updates since then, its release cadence is effectively non-existent, indicating an abandoned or legacy status despite an 'active' project badge from its active development period. Its key differentiators at the time included robust compatibility with Connect and Express middleware, as well as plain Node.js `http` servers, providing granular control over CORS policies for various server setups. Developers should be aware of its CommonJS-only nature and lack of ongoing maintenance.
Common errors
-
TypeError: corser.create is not a function
cause Attempting to use `import corser from 'corser';` or `import * as corser from 'corser';` which incorrectly handles the CommonJS default export, or trying to destructure a non-existent named export.fixUse the correct CommonJS `require` syntax: `const corser = require('corser');` then `corser.create()`. -
ReferenceError: require is not defined
cause Attempting to use `require('corser')` within an ES Module (type: 'module' in package.json or .mjs file) context in Node.js.fixEither convert your project to CommonJS (remove 'type: module' from package.json) or use a different CORS middleware that supports ES Modules. You could also explore `createRequire` for advanced interoperability, but it's generally not recommended for simple imports. -
Access to fetch at '...' from origin '...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
cause The `origins` configuration in `corser.create()` is either too restrictive, the requested origin is not whitelisted, or the dynamic origin function is failing to match.fixEnsure the `origins` array explicitly includes the client's origin (e.g., `['http://localhost:3000']`) or that your dynamic origin function correctly returns `true` for the callback. Check for typos in the origin URL. Also ensure Corser middleware is applied correctly and not skipped. -
The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
cause CORS middleware is being applied multiple times in the request processing chain, leading to duplicate 'Access-Control-Allow-Origin' headers.fixReview your middleware setup to ensure `app.use(corser.create())` or similar is called only once per request or once during app initialization. This often happens if it's included in a generic router that's also mounted globally.
Warnings
- breaking In version 2.0.0, the default behavior for preflight requests changed: they are now automatically closed. To retain previous behavior (where you handle OPTIONS requests yourself), you must explicitly set `endPreflightRequests` to `false` in the configuration object.
- breaking The callback function for dynamic origin checking changed its signature in v2.0.0 from `(matches)` to `(err, matches)`. Existing implementations relying on the old signature will break.
- gotcha Corser is a CommonJS-only package. Attempting to import it using ES Module `import` syntax will result in errors in modern Node.js environments unless a compatible transpiler or loader is used.
- gotcha The package has not been updated since August 2016. This means it lacks support for newer Node.js features, potential security updates, or bug fixes for modern browser behaviors beyond what was addressed in v2.0.1 for Chrome 52.
Install
-
npm install corser -
yarn add corser -
pnpm add corser
Imports
- corser
import corser from 'corser'; import { create } from 'corser';const corser = require('corser'); - corser.create
import { create } from 'corser'; const corserMiddleware = create();const corser = require('corser'); const corserMiddleware = corser.create();
Quickstart
const express = require('express');
const corser = require('corser');
const app = express();
// Configure Corser to allow all origins by default.
// For production, specify a whitelist: corser.create({ origins: ['http://localhost:3000'] })
app.use(corser.create());
app.get('/', function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Nice weather today, huh?');
});
app.listen(1337, () => {
console.log('Server listening on http://localhost:1337');
});
// To run this example:
// 1. npm install express corser
// 2. node your_script.js