Simple CORS Middleware for Micro
micro-cors is a straightforward middleware designed to enable Cross-Origin Resource Sharing (CORS) for applications built with `micro`, a minimalist asynchronous HTTP microservices framework. The package's current stable version is `0.1.1`, which was last published approximately seven years ago. While `1.0.0-alpha` versions were released around five years ago, indicating a past attempt at a major update, development appears to have stalled in alpha, leaving the `0.x` branch as the de facto stable release. It maintains a slow release cadence, essentially being in a maintenance mode. Its key differentiator is its small footprint and specific integration with the `micro` ecosystem, aiming for minimal configuration to handle CORS headers.
Common errors
-
Cannot read property 'setHeader' of undefined
cause This error can occur if the `micro-cors` middleware is not correctly applied to the `micro` handler, or if the `res` object is not correctly propagated or is somehow lost in the middleware chain. It can also happen if the `micro-cors` function is called without immediately invoking its result (e.g., `require('micro-cors')` instead of `require('micro-cors')()`).fixEnsure `module.exports = cors(handler)` is used and that `cors` is the result of `microCors()` or `microCors(options)`. -
TypeScript error: Cannot find module 'micro-cors' or its corresponding type declarations.
cause The `micro-cors` package does not ship with its own TypeScript declaration files.fixInstall the community-maintained type definitions: `npm install --save-dev @types/micro-cors` or `yarn add -D @types/micro-cors`. -
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [URL]. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
cause The server-side CORS configuration is either missing the `Access-Control-Allow-Origin` header, or its value does not match the origin of the requesting client. This can happen if the `origin` option in `micro-cors` is too restrictive or not set correctly.fixVerify the `origin` option in `micro-cors` is set to match the client's origin (e.g., `origin: 'http://localhost:3000'`) or `origin: '*'` for public APIs (but be mindful of security implications). For local development, `origin: '*'` is often used. Ensure preflight `OPTIONS` requests are handled correctly and send the necessary `Access-Control-Allow-Origin` header.
Warnings
- breaking The `micro` framework, which `micro-cors` is built upon, explicitly states it is 'not intended for use in serverless environments'. This means `micro-cors` may not be suitable for serverless functions, a common deployment target for `micro` historically.
- gotcha The `0.x` stable branch has not been updated in approximately seven years, and the `1.0.0-alpha` releases from five years ago appear stalled, with open issues indicating they are not fully functional due to dependencies like Babel. This indicates the package is largely unmaintained.
- gotcha When `allowCredentials` is set to `true`, the `origin` option cannot be set to `'*'`. This is a standard CORS security restriction.
- gotcha Incorrect handling of `OPTIONS` preflight requests can lead to unexpected CORS errors or unnecessary execution of your main handler. Prior to `v1` (which is in alpha), `micro-cors` only sets headers in the response and requires manual handling for preflight requests if you want to avoid triggering your main handler.
Install
-
npm install micro-cors -
yarn add micro-cors -
pnpm add micro-cors
Imports
- microCors
import { microCors } from 'micro-cors';import microCors from 'micro-cors'; const cors = microCors();
- cors
const { cors } = require('micro-cors');const cors = require('micro-cors')(); - Options
const cors = microCors({ methods: ['GET', 'POST'] });const cors = microCors({ allowMethods: ['GET', 'POST'] });
Quickstart
import { send } from 'micro';
import microCors from 'micro-cors';
const cors = microCors({
allowMethods: ['GET', 'POST', 'OPTIONS'],
allowHeaders: ['X-Requested-With', 'Access-Control-Allow-Origin', 'X-HTTP-Method-Override', 'Content-Type', 'Authorization', 'Accept'],
origin: '*'
});
const handler = async (req, res) => {
if (req.method === 'OPTIONS') {
// Handle preflight requests explicitly if needed
return send(res, 200, 'ok!');
}
if (req.method === 'POST') {
// Example POST request handling
const data = await json(req);
return send(res, 200, { message: 'Received POST data', data });
}
// Default GET response
return send(res, 200, { message: 'Hello from micro-cors!' });
};
export default cors(handler);