XCors

The XCors class provides a simple outbound middleware for setting CORS (Cross-Origin Resource Sharing) headers on responses. It automatically registers to the global router on instantiation. See MDN: Cross-Origin Resource Sharing for detailed CORS concepts.

Contents
  1. Usage
  2. Constructor Parameters
  3. Preflight Handling

Usage

Basic CORS setup

import { X } from "@ozanarslan/corpus";

new X.Cors({
	allowedOrigins: ["https://example.com", "https://app.example.com"],
	allowedMethods: ["GET", "POST", "PUT", "DELETE"],
	allowedHeaders: ["Content-Type", "Authorization"],
});

With credentials and exposed headers

new X.Cors({
	allowedOrigins: ["https://trusted.com"],
	credentials: true,
	exposedHeaders: ["X-Request-Id", "X-Rate-Limit"],
});

Constructor Parameters

opts

CorsOptions | undefined

CORS configuration options. Pass undefined for permissive defaults (wildcard origin, no credentials).

Option Type Default Description
allowedOrigins string[] ["*"] Origins permitted to access the resource. When credentials is true, wildcard is not allowed — the actual request origin is reflected instead.
allowedMethods string[] HTTP methods allowed. Sets Access-Control-Allow-Methods.
allowedHeaders CHeaderKey[] Headers clients may send. Sets Access-Control-Allow-Headers.
exposedHeaders CHeaderKey[] Response headers exposed to client JavaScript. Sets Access-Control-Expose-Headers.
credentials boolean Whether to expose cookies and auth headers. Sets Access-Control-Allow-Credentials.
maxAge number 86400 How long preflight results can be cached in seconds. Sets Access-Control-Max-Age.

Preflight Handling

XCors exposes a getPreflightHandler() method that returns a request handler suitable for server.handlePreflight. This handles OPTIONS preflight requests with the same origin logic as the outbound middleware, and additionally sets the Access-Control-Max-Age header.

import { C, X } from "@ozanarslan/corpus";

const server = new C.Server();
const cors = new X.Cors({ allowedOrigins: ["https://example.com"] });

// handled internally:
// protected handlePreflight: RequestHandler = async (req) => {
// 	const cors = $routerStore.get().cors;
// 	if (!cors) {
// 		return new CResponse(undefined, { status: Status.NO_CONTENT });
// 	}
// 	const handler = cors.getPreflightHandler();
// 	return await handler(req);
// };