@nhankyjangchan/koa-cors
v2.1.4
Published
Cross-Origin Resource Sharing (CORS) middleware for KoaJS written in TypeScript
Maintainers
Readme
@nhankyjangchan/koa-cors
📌 Formerly published as @nhankyjangchan/koajs-cors, which is now a legacy package. Instead of it, use current package
Cross-Origin Resource Sharing (CORS) for KoaJS written in TypeScript
Handles CORS requests by setting appropriate headers for both simple requests and preflight (OPTIONS) requests. Validates the Origin header against the configured whitelist and throws a 403 error for unauthorized origins. Throws a 500 error if the origin option is set to an invalid type.
Automatically adds Vary: Origin header to all responses to ensure proper caching behaviour when different origins may receive different headers.
✨ Features
- Static or dynamic origin validation (string, Set, or function, including async)
- Dynamic credentials resolution (boolean or function, including async)
- Automatic rejection of unauthorized origins (403) and invalid configuration (500)
- Automatically adds
Vary: Originheader for proper caching - Proper merging of
Varyheaders during error handling (deduplication, lowercasing) - Preflight (OPTIONS) request handling with method and header validation
- Configurable preflight caching via
Access-Control-Max-Age - Automatic echo of
Access-Control-Request-HeaderswhenallowHeadersis not set - Credentials support with automatic
*to explicit origin conversion (CORS spec compliance) - Private Network Access support (preflight requests from public to private networks)
- Cross-Origin-Opener-Policy (
same-origin) and Cross-Origin-Embedder-Policy (require-corp) headers - Error handling with CORS header preservation (
keepHeadersOnError) - Safe handling of non-Error throwables (primitives are wrapped in Error instances)
- Conditional skipping of CORS processing (
shouldSkip) - Zero external dependencies
- Full TypeScript support with dedicated types in the
Pluginnamespace - Built-in support for ESM and CJS
ℹ️ Note (For version lower than v2.0.0)
This package was previously published as
@nhankyjangchan/koajs-cors. Starting with v1.4.0, this package has been migrated to a new name: @nhankyjangchan/koa-cors. If you're still using legacy @nhankyjangchan/koajs-cors, please migrate to new package, because this is now deprecated and receives security fixes only. Migration is seamless, just install the new package and swap the package name in yourpackage.jsonand import statements. The API remains unchanged.
📦 Installation
$ npm i @nhankyjangchan/koa-corsor
$ bun add @nhankyjangchan/koa-corsand if you use TS, don't forget to install types for Koa
$ npm i -D @types/koa⚙️ Options
/**
* CORS middleware configuration options.
* @see https://fetch.spec.whatwg.org/#http-cors-protocol
*/
export interface Options {
/**
* Configure the `Access-Control-Allow-Origin` header.
*
* @default '*'
* @see https://fetch.spec.whatwg.org/#http-origin
*/
origin?: string | Set<string> | (ctx: Context) => string | Promise<string>;
/**
* Configure the `Access-Control-Allow-Credentials` header.
*
* @default false
* @see https://fetch.spec.whatwg.org/#http-access-control-allow-credentials
*/
credentials?: boolean | (ctx: Context) => boolean | Promise<boolean>;
/**
* Configure the `Access-Control-Allow-Methods` header.
*
* @default ['HEAD', 'POST', 'GET', 'PATCH', 'PUT', 'DELETE']
* @see https://fetch.spec.whatwg.org/#http-access-control-allow-methods
*/
allowMethods?: string | string[];
/**
* Configure the `Access-Control-Allow-Headers` header.
*
* @default undefined
* @see https://fetch.spec.whatwg.org/#http-access-control-allow-headers
*/
allowHeaders?: string | string[];
/**
* Configure the `Access-Control-Max-Age` header (in seconds).
*
* @default '3600'
* @see https://fetch.spec.whatwg.org/#http-access-control-max-age
*/
maxAge?: string | number;
/**
* Configure the `Access-Control-Expose-Headers` header.
*
* @default undefined
* @see https://fetch.spec.whatwg.org/#http-access-control-expose-headers
*/
exposeHeaders?: string | string[];
/**
* Enable Private Network Access handling.
*
* @default false
* @see https://wicg.github.io/private-network-access/#headers
*/
privateNetworkAccess?: boolean;
/**
* Enable `Cross-Origin-Opener-Policy` header.
*
* @default false
* @see https://html.spec.whatwg.org/dev/browsers.html#cross-origin-opener-policies
*/
originOpenerPolicy?: boolean;
/**
* Enable `Cross-Origin-Embedder-Policy` header.
*
* @default false
* @see https://html.spec.whatwg.org/dev/browsers.html#the-coep-headers
*/
originEmbedderPolicy?: boolean;
/**
* Keep CORS headers when an error is thrown during request processing.
* When enabled, CORS headers are attached to the `err.headers` object,
* ensuring they are sent even in error responses.
*
* The middleware also properly merges the `Vary: Origin` header with any
* existing `Vary` headers from the error object, deduplicating field names
* and converting them to lowercase for consistency.
*
* @default true
*/
keepHeadersOnError?: boolean;
/**
* Conditionally skip CORS processing for specific requests.
*
* Accepts a function that receives the Koa context and returns a boolean
* (or a Promise resolving to a boolean). If the function returns `true`,
* the middleware immediately calls `next()` without adding any CORS headers.
*
* @default false
*/
shouldSkip?: false | (ctx: Context) => boolean | Promise<boolean>;
}🔧 Default options
/**
* CORS middleware default configuration options.
*/
const defaultOptions: Options = {
origin: '*',
credentials: false,
allowMethods: ['HEAD', 'POST', 'GET', 'PATCH', 'PUT', 'DELETE'],
maxAge: '3600',
privateNetworkAccess: false,
originOpenerPolicy: false,
originEmbedderPolicy: false,
keepHeadersOnError: true,
shouldSkip: false
};🛠️ Usage
/**
* File `src/plugins/cors.plugin.ts`.
*/
import koaCors from '@nhankyjangchan/koa-cors';
import type { Options } from '@nhankyjangchan/koa-cors';
import type { Middleware } from 'koa';
export const corsPlugin: Middleware = (function () {
const options: Options = {
origin: 'https://example.com',
credentials: true,
allowMethods: ['HEAD', 'GET', 'POST', 'PUT', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization'],
maxAge: 3600,
exposeHeaders: ['X-Pagination-Offset', 'X-Response-Time'],
privateNetworkAccess: false,
originOpenerPolicy: false,
originEmbedderPolicy: false,
keepHeadersOnError: true,
shouldSkip: false
};
return koaCors(options);
})();
/**
* File `src/app.ts`.
*/
import Koa from 'koa';
import { corsPlugin } from './plugins/cors.plugin.ts';
const app = new Koa();
app.use(corsPlugin);
// ...
app.listen(3000);🧪 Tests
$ bun test --coverage