npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nhankyjangchan/koa-cors

v2.1.4

Published

Cross-Origin Resource Sharing (CORS) middleware for KoaJS written in TypeScript

Readme

@nhankyjangchan/koa-cors

📌 Formerly published as @nhankyjangchan/koajs-cors, which is now a legacy package. Instead of it, use current package

npm version github repo node version bun version coverage tests npm downloads unpacked Size last update license

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: Origin header for proper caching
  • Proper merging of Vary headers 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-Headers when allowHeaders is 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 Plugin namespace
  • 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 your package.json and import statements. The API remains unchanged.

📦 Installation

$ npm i @nhankyjangchan/koa-cors

or

$ bun add @nhankyjangchan/koa-cors

and 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

📋 Releases

CHANGELOG

📄 Docs

DOCUMENTATION

🪪 License

MIT