Koa2 CORS Middleware

raw JSON →
2.0.6 verified Thu Apr 23 auth: no javascript

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.

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.
cause The Koa server's CORS configuration does not allow the requesting origin.
fix
Ensure the 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
cause Attempting to destructure a CommonJS default export or incorrect ESM import for `koa2-cors`.
fix
For CommonJS, use 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.
cause The installed Node.js version does not meet the minimum requirement of `koa2-cors` v2.0.6+.
fix
Upgrade your Node.js runtime environment to version 7.6.0 or newer.
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.
fix Upgrade your Node.js runtime to version 7.6.0 or newer to ensure compatibility.
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.
fix If `credentials: true` is needed, configure the `origin` option to return a specific allowed domain (e.g., `'http://localhost:8080'`) or an array of allowed domains, rather than `'*'`. This is a fundamental CORS security constraint.
gotcha Incorrectly configured `origin` functions can inadvertently open your API to unwanted domains or block legitimate ones. Always test dynamic origin logic thoroughly.
fix Carefully define the logic within the `origin` function. Ensure it accurately identifies and allows only trusted origins, returning `false` or a specific origin as required by your application's security policy.
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.
fix No direct action required, but be aware that older versions might have different build-time dependencies or output. Newer versions are likely more streamlined.
npm install koa2-cors
yarn add koa2-cors
pnpm add koa2-cors

This quickstart demonstrates how to apply the koa2-cors middleware to a Koa application, showing both basic usage and advanced configuration with various CORS options, including a dynamic origin function.

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');
});