Koa2 CORS Middleware
raw JSON →koa2-cors is a Koa 2.x middleware for handling Cross-Origin Resource Sharing (CORS) headers. It simplifies the implementation of CORS policies in Koa applications, allowing developers to configure the `Access-Control-Allow-Origin`, `Access-Control-Expose-Headers`, `Access-Control-Max-Age`, `Access-Control-Allow-Credentials`, `Access-Control-Allow-Methods`, and `Access-Control-Allow-Headers` through a straightforward options object or a dynamic function for the origin. The current stable version is 2.0.6. The package has seen sporadic updates, with recent releases focusing on compatibility (e.g., removing Babel in v2.0.5) and ensuring correct header behavior (v2.0.6 always sets `Vary: Origin`). It requires Node.js v7.6.0 or higher. Its key differentiator is its direct integration and simplicity within the Koa 2.x ecosystem, providing a robust and easy-to-configure solution for common CORS requirements without over-complication.
Common errors
error Access to fetch at 'http://api.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ↓
origin option in koa2-cors is correctly configured to allow 'http://localhost:3000' or '*' (if credentials is false). error TypeError: cors is not a function ↓
const cors = require('koa2-cors');. For ESM, use import cors from 'koa2-cors';. error Error: Your node version is too old. koa2-cors requires node v7.6.0 or higher. ↓
Warnings
breaking Version 2.0.6 and later requires Node.js v7.6.0 or higher. Applications running on older Node.js versions will fail to start. ↓
gotcha When `credentials` is set to `true`, the `origin` option cannot be set to `*`. It must be a specific origin or a function that returns a specific origin. ↓
gotcha Incorrectly configured `origin` functions can inadvertently open your API to unwanted domains or block legitimate ones. Always test dynamic origin logic thoroughly. ↓
deprecated Previous versions (prior to v2.0.5) included Babel for transpilation. While this is not directly user-facing, it indicates a shift in the build process. ↓
Install
npm install koa2-cors yarn add koa2-cors pnpm add koa2-cors Imports
- cors wrong
const { cors } = require('koa2-cors');correctconst cors = require('koa2-cors'); - cors wrong
import { cors } from 'koa2-cors';correctimport cors from 'koa2-cors';
Quickstart
const Koa = require('koa');
const cors = require('koa2-cors');
const app = new Koa();
// Basic usage
app.use(cors());
// Advanced usage with options
app.use(cors({
origin: function(ctx) {
// Dynamically set origin based on request context
if (ctx.url === '/test') {
return false; // Block CORS for /test path
}
return '*'; // Allow all origins for other paths
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5, // Preflight request cache max age in seconds
credentials: true, // Allow sending cookies/auth headers with cross-origin requests
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
app.use(async ctx => {
ctx.body = 'Hello Koa!';
});
app.listen(3000, () => {
console.log('Koa server running on http://localhost:3000');
});