Skip to content
MMT40Public

About

Explain browser CORS decisions with typed, actionable diagnostics.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

of-CORS shield logo

of-cors

CORS decisions, explained.

Describe a browser request and its CORS response headers, then get a typed decision with actionable diagnostics—without making a network request.

GitHub Actions CI npm version npm downloads MIT licence

of-cors is a side-effect-free TypeScript library for Node.js, modern browsers, and edge runtimes. The caller supplies the request and response information; the library explains the CORS decision and never changes server configuration.

Why of-cors?

  • Actionable results: stable issue codes, severities, concise messages, and practical fixes.
  • Typed by default: clear TypeScript inputs and immutable result types.
  • Runtime-neutral: ESM and CommonJS builds with no runtime dependencies or Node-only APIs.
  • Explicit inputs: analyze captured or hypothetical headers without performing a request.

Installation

npm install of-cors

Both ESM and CommonJS consumers are supported:

import { analyzeCors } from 'of-cors';
const { analyzeCors } = require('of-cors');

Quick start

import { analyzeCors } from 'of-cors';

const result = analyzeCors({
  request: {
    origin: 'https://app.example.com',
    url: 'https://api.example.com/users',
    method: 'GET',
  },
  response: {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': 'https://app.example.com',
    },
  },
});

result.allowed; // true
result.stage; // "response"
result.issues; // []

Failed-request diagnostics

const result = analyzeCors({
  request: {
    origin: 'https://app.example.com',
    url: 'https://api.example.com/users',
    method: 'PATCH',
    headers: {
      Authorization: 'Bearer token',
      'Content-Type': 'application/json',
    },
    credentials: 'include',
  },
  preflightResponse: {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': 'https://app.example.com',
      'Access-Control-Allow-Methods': 'GET, POST, PATCH',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Access-Control-Allow-Credentials': 'true',
    },
  },
});

console.log(result.allowed); // false
console.log(result.stage); // "preflight"
console.log(result.issues.map((issue) => issue.code));
// [
//   "PREFLIGHT_METHOD_NOT_SAFELISTED",
//   "PREFLIGHT_HEADERS_NOT_SAFELISTED",
//   "HEADER_NOT_ALLOWED"
// ]

The request is rejected because Authorization caused a preflight but was not included in Access-Control-Allow-Headers. Each issue has a stable code, a severity, a human-readable message, and usually a practical suggestion.

Simple requests

A cross-origin request that does not require preflight needs the actual resource response:

const result = analyzeCors({
  request: {
    origin: 'https://app.example.com',
    url: 'https://api.example.com/health',
    method: 'GET',
  },
  response: {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
});

result.allowed; // true
result.preflightRequired; // false

Preflight and actual responses

For a preflighted request, pass preflightResponse to determine whether the browser may send the actual request. If the resource response is also available, pass it as response to complete the analysis:

const result = analyzeCors({
  request: {
    origin: 'https://app.example.com',
    url: 'https://api.example.com/users/42',
    method: 'DELETE',
  },
  preflightResponse: {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'DELETE',
    },
  },
  response: {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
});

result.allowed; // true
result.stage; // "response"

Result stages

stage Meaning
same-origin CORS does not apply and response headers are not inspected.
preflight The OPTIONS response failed, or it passed and no actual response was supplied.
response The actual cross-origin response was evaluated, or is required but was not supplied.

When a preflight-only result has allowed: true, the browser may send the actual request. It does not mean that the eventual resource response is guaranteed to pass its own CORS check.

Public API

analyzeCors(input)

Returns an immutable CorsAnalysisResult:

interface CorsAnalysisResult {
  readonly allowed: boolean;
  readonly crossOrigin: boolean;
  readonly preflightRequired: boolean;
  readonly stage: 'same-origin' | 'preflight' | 'response';
  readonly issues: readonly CorsIssue[];
}

The package also exports TypeScript types for every public input and result, including AnalyzeCorsInput, CorsRequest, CorsResponse, CorsIssue, and CorsIssueCode.

Ordinary CORS failures never throw. analyzeCors throws TypeError only for invalid API input, such as a malformed URL, HTTP method or header, an unsupported credentials value, or an invalid response status. request.url must be an absolute HTTP(S) URL without embedded credentials. request.origin must contain only an HTTP(S) scheme, host, and optional port; the serialized opaque origin "null" is also accepted.

Supported rules

The initial release models the relevant parts of the current Fetch Standard CORS algorithm, including:

  • same-origin comparison with default-port normalization;
  • Fetch-compatible method normalization and CORS-safelisted methods;
  • safelisted request header names, values, content types, lengths, and single byte ranges;
  • the method and header names that cause preflight;
  • preflight 2xx status and allow-method/allow-header checks;
  • exact and wildcard allowed origins;
  • credentialed request restrictions and the case-sensitive true credentials value;
  • case-insensitive HTTP header names and case-sensitive HTTP method tokens;
  • the special rule that Access-Control-Allow-Headers: * never covers Authorization.

request.headers must contain only author-controlled headers, such as those passed to fetch. Supplying a browser-managed header such as Origin or Cookie is invalid input and throws TypeError.

Limitations

This version intentionally does not model redirects, the browser's preflight cache, Private Network Access, response-header exposure, cookies, or general HTTP/network success. For example, a 404 response can still be CORS-allowed when its CORS headers are valid.

Development

Development requires Node.js 20.19 or later.

npm ci
npm run check

Available scripts:

  • npm run build builds ESM, CommonJS, source maps, and declarations into dist/.
  • npm test runs the Vitest suite once.
  • npm run test:watch runs Vitest in watch mode.
  • npm run lint checks the project with ESLint.
  • npm run format formats the project with Prettier.
  • npm run format:check verifies formatting without changing files.
  • npm run typecheck checks the project in TypeScript strict mode without emitting files.
  • npm run check runs formatting checks, linting, type checking, tests, and a production build.

During publication, prepublishOnly runs the non-build checks and prepack creates one fresh production build. Keeping the build in prepack avoids running it twice in the normal npm publish lifecycle while still ensuring the tarball contains current output.

Before publishing, inspect the package allowlist with npm pack --dry-run.

Community

See the contribution guide, security policy, and Code of Conduct before participating.

License

MIT

About

Explain browser CORS decisions with typed, actionable diagnostics.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages