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.
npm install koa2-corsVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your Node.js runtime to version 7.6.0 or newer to ensure compatibility.
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.
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.
No direct action required, but be aware that older versions might have different build-time dependencies or output. Newer versions are likely more streamlined.
Ensure the `origin` option in `koa2-cors` is correctly configured to allow `'http://localhost:3000'` or `'*'` (if `credentials` is `false`).
For CommonJS, use `const cors = require('koa2-cors');`. For ESM, use `import cors from 'koa2-cors';`.Upgrade your Node.js runtime environment to version 7.6.0 or newer.
No dependency data recorded yet.