{"id":17768,"library":"koa2-cors","title":"Koa2 CORS Middleware","description":"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.","status":"active","version":"2.0.6","language":"javascript","source_language":"en","source_url":"https://github.com/zadzbw/koa2-cors","tags":["javascript","koa2","cors","middleware"],"install":[{"cmd":"npm install koa2-cors","lang":"bash","label":"npm"},{"cmd":"yarn add koa2-cors","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa2-cors","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package exports a single function as its default (CommonJS) export.","wrong":"const { cors } = require('koa2-cors');","symbol":"cors","correct":"const cors = require('koa2-cors');"},{"note":"For ESM environments, use a default import as the package exports a single function.","wrong":"import { cors } from 'koa2-cors';","symbol":"cors","correct":"import cors from 'koa2-cors';"}],"quickstart":{"code":"const Koa = require('koa');\nconst cors = require('koa2-cors');\n\nconst app = new Koa();\n\n// Basic usage\napp.use(cors());\n\n// Advanced usage with options\napp.use(cors({\n  origin: function(ctx) {\n    // Dynamically set origin based on request context\n    if (ctx.url === '/test') {\n      return false; // Block CORS for /test path\n    }\n    return '*'; // Allow all origins for other paths\n  },\n  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],\n  maxAge: 5, // Preflight request cache max age in seconds\n  credentials: true, // Allow sending cookies/auth headers with cross-origin requests\n  allowMethods: ['GET', 'POST', 'DELETE'],\n  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],\n}));\n\napp.use(async ctx => {\n  ctx.body = 'Hello Koa!';\n});\n\napp.listen(3000, () => {\n  console.log('Koa server running on http://localhost:3000');\n});","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 7.6.0 or newer to ensure compatibility.","message":"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.","severity":"breaking","affected_versions":">=2.0.6"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Incorrectly configured `origin` functions can inadvertently open your API to unwanted domains or block legitimate ones. Always test dynamic origin logic thoroughly.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"deprecated","affected_versions":"<2.0.5"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the `origin` option in `koa2-cors` is correctly configured to allow `'http://localhost:3000'` or `'*'` (if `credentials` is `false`).","cause":"The Koa server's CORS configuration does not allow the requesting origin.","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."},{"fix":"For CommonJS, use `const cors = require('koa2-cors');`. For ESM, use `import cors from 'koa2-cors';`.","cause":"Attempting to destructure a CommonJS default export or incorrect ESM import for `koa2-cors`.","error":"TypeError: cors is not a function"},{"fix":"Upgrade your Node.js runtime environment to version 7.6.0 or newer.","cause":"The installed Node.js version does not meet the minimum requirement of `koa2-cors` v2.0.6+.","error":"Error: Your node version is too old. koa2-cors requires node v7.6.0 or higher."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}