CORS Handling Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in TypeScript as in every other language.
- ✓There is no runtime of its own to name here; TypeScript borrows the host it compiles against.
- ✓The allowlist carries as const so it becomes a readonly tuple of string literals, the union comes from (typeof ALLOWED)[number], and narrowing runs through a user-defined type guard rather than a bare boolean helper.
- ✓The TypeScript trap: ALLOWED.includes(origin) refuses to compile once ALLOWED is a const tuple. includes is typed as (item: 'https://app.example.dev' | 'https://ops.example.dev') => boolean, so handing it a string is error TS2345, and both usual escapes differ enormously.
- ✓Every type-level construct above costs exactly zero at runtime, and that is the trap: the union, the satisfies clause and the predicate signature are erased by tsc, leaving only whatever your guard body actually does.
What CORS Handling actually is
CORS Handling in TypeScript: what you actually reach for
TypeScript implementation
// Fetch-standard handler: the shape Hono, Deno.serve, Bun.serve and route handlers take.
const ALLOWED = ['https://app.example.dev', 'https://ops.example.dev'] as const;
type AllowedOrigin = (typeof ALLOWED)[number];
// The widening cast is load-bearing: ALLOWED.includes(o) with o: string is TS2345,
// because a readonly tuple types includes() as (item: AllowedOrigin) => boolean.
const isAllowed = (o: string | null): o is AllowedOrigin => o !== null && (ALLOWED as readonly string[]).includes(o);
interface CorsPolicy {
readonly methods: readonly string[];
readonly reqHeaders: readonly string[];
readonly exposed: readonly string[];
readonly maxAge: number;
}
const POLICY = {
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
reqHeaders: ['content-type', 'authorization'],
exposed: ['X-Request-Id', 'X-Rate-Limit-Remaining'],
maxAge: 600,
} as const satisfies CorsPolicy; // checks the shape without widening 600 to number
function baseHeaders(origin: AllowedOrigin): Headers {
const h = new Headers({ 'Access-Control-Allow-Origin': origin, Vary: 'Origin' });
h.set('Access-Control-Allow-Credentials', 'true');
h.set('Access-Control-Expose-Headers', POLICY.exposed.join(', '));
return h;
}
export async function withCors(req: Request, next: (r: Request) => Promise<Response>) {
const origin = req.headers.get('origin'); // string | null, never undefined
if (!isAllowed(origin)) return next(req);
if (req.method === 'OPTIONS' && req.headers.has('access-control-request-method')) {
const h = baseHeaders(origin); // origin is narrowed to AllowedOrigin
h.append('Vary', 'Access-Control-Request-Headers');
h.set('Access-Control-Allow-Methods', POLICY.methods.join(', '));
h.set('Access-Control-Allow-Headers', POLICY.reqHeaders.join(', '));
h.set('Access-Control-Max-Age', String(POLICY.maxAge));
return new Response(null, { status: 204, headers: h });
}
const res = await next(req);
const merged = new Headers(res.headers);
baseHeaders(origin).forEach((v, k) => merged.append(k, v));
return new Response(res.body, { status: res.status, headers: merged });
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for CORS Handling?
There is no runtime of its own to name here; TypeScript borrows the host it compiles against. Request, Response and Headers arrive from lib.dom.d.ts or from the undici declarations in @types/node, and that is the shape Hono, Deno.serve, Bun.serve and modern route handlers all accept. Under Express you instead get RequestHandler from @types/express, whose req.headers is IncomingHttpHeaders: known names typed string | undefined, everything else string | string[] | undefined through the index signature. Every CORS header, including access-control-request-headers, is one of those known names and stays typed string | undefined; a header the declarations do not list, like a custom x-request-id, is what actually falls through the index signature and types as a possible array.
What is the most common TypeScript mistake when implementing CORS Handling?
ALLOWED.includes(origin) refuses to compile once ALLOWED is a const tuple. includes is typed as (item: 'https://app.example.dev' | 'https://ops.example.dev') => boolean, so handing it a string is error TS2345, and both usual escapes differ enormously. Widening with as readonly string[] is correct. Casting the argument with as AllowedOrigin is a claim the compiler simply believes, after which the comparison still runs but the reviewer has lost the guarantee. The deeper trap: a type predicate is trusted, never verified, so a wrong guard body erases to nothing and ships an allowlist that admits every origin while type-checking clean.
How does CORS Handling actually perform in TypeScript?
Every type-level construct above costs exactly zero at runtime, and that is the trap: the union, the satisfies clause and the predicate signature are erased by tsc, leaving only whatever your guard body actually does. A tuple scan is linear, so an allowlist loaded from configuration belongs in a Set<string> built once at module load rather than re-scanned per call. The real allocation is structural: cloning a Response to merge headers builds a fresh normalised header map and a fresh Response wrapper on every single request. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.