How OmniRoute Handles CORS Requests: A Complete Technical Guide
OmniRoute implements a centralized, declarative CORS strategy through static headers defined in src/shared/utils/cors.ts and dynamic origin resolution managed by src/server/cors/origins.ts, ensuring consistent cross-origin handling across all API routes via environment-driven configuration.
OmniRoute, an open-source API routing layer, provides a robust Cross-Origin Resource Sharing (CORS) mechanism designed to handle browser-based cross-origin requests securely. The implementation centers on a single source of truth pattern that eliminates configuration drift while supporting both wildcard and whitelist-based origin policies. Every API response, including error responses, inherits the correct CORS headers through a composable utility system.
Centralized CORS Configuration
The foundation of OmniRoute's CORS handling resides in src/shared/utils/cors.ts, which exports the canonical header set used throughout the application.
Static CORS Headers
The CORS_HEADERS constant defines the mandatory headers applied to every response:
// src/shared/utils/cors.ts
export const CORS_HEADERS = {
"Access-Control-Allow-Methods": "OPTIONS, GET, POST, PUT, DELETE, PATCH",
"Access-Control-Allow-Headers":
"Authorization, Content-Type, Accept, X-Omni-Request-ID, X-Omni-Client",
};
Route handlers compose these headers into specialized sets as needed. For JSON responses, the system creates JSON_HEADERS by spreading CORS_HEADERS and appending the content type:
const JSON_HEADERS = {
...CORS_HEADERS,
"Content-Type": "application/json"
};
Pre-Flight Request Helper
The handleCorsOptions() function provides a standardized pre-flight response. Exported from the same utilities file, it returns a 204 No Content response carrying the complete CORS header set:
export function handleCorsOptions() {
return new Response(null, {
status: 204,
headers: CORS_HEADERS
});
}
This ensures that every OPTIONS endpoint returns an identical response, simplifying route implementations.
Dynamic Origin Resolution
While static headers cover methods and allowed headers, the Access-Control-Allow-Origin value requires runtime resolution based on environment configuration. This logic lives in src/server/cors/origins.ts.
Environment-Driven Configuration
The origin resolution system reads three environment variables:
CORS_ALLOW_ALL– When truthy, the server echoes back anyOriginheader (allow-all mode)CORS_ALLOWED_ORIGINS– Comma-separated whitelist of explicit originsCORS_ORIGIN– Legacy variable maintained for backward compatibility
Runtime Origin Selection
The module exports STATIC_CORS_HEADERS, a frozen object that combines the base headers with the dynamically resolved origin:
// src/server/cors/origins.ts
export const STATIC_CORS_HEADERS: Readonly<Record<string, string>> = Object.freeze({
...CORS_HEADERS,
"Access-Control-Allow-Origin": resolveOrigin(request),
});
The resolveOrigin() function inspects the incoming request's Origin header, validates it against the whitelist (or returns the wildcard * when CORS_ALLOW_ALL is enabled), and returns the appropriate value. If no origin is supplied and allow-all mode is active, the wildcard applies.
Route-Level Integration
Every public API route imports these utilities to ensure consistent CORS handling. The pattern guarantees that all responses, including errors, carry the correct headers.
Standard Route Implementation
Routes typically implement both the primary method handler and an OPTIONS handler:
import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
export async function GET(req: Request) {
const data = await fetchData();
return new Response(JSON.stringify(data), {
status: 200,
headers: { ...CORS_HEADERS, "Content-Type": "application/json" },
});
}
export async function OPTIONS() {
return handleCorsOptions();
}
Middleware Integration
The CORS utilities integrate into middleware layers such as src/shared/middleware/requireJsonContentType.ts, which merges CORS_HEADERS into responses enforcing JSON content type requirements. This ensures that validation errors themselves remain accessible to cross-origin clients.
Testing and Validation
OmniRoute maintains comprehensive test coverage for CORS behavior across unit and integration suites.
Unit Testing
The file tests/unit/cors/origins.test.ts validates:
- Allow-all logic and wildcard generation
- Whitelist parsing from
CORS_ALLOWED_ORIGINS - Legacy environment variable fallback behavior
- Immutability of
STATIC_CORS_HEADERS
Integration Testing
Integration tests in tests/integration/proxy-pipeline.test.ts verify that every public route exports the expected CORS headers during pre-flight requests. These tests confirm that the centralized configuration propagates correctly through the routing layer.
Summary
- Centralized configuration in
src/shared/utils/cors.tsprovides theCORS_HEADERSconstant andhandleCorsOptions()helper used by every route. - Dynamic origin resolution in
src/server/cors/origins.tsevaluatesCORS_ALLOW_ALL,CORS_ALLOWED_ORIGINS, andCORS_ORIGINto set the correctAccess-Control-Allow-Originvalue. - Declarative integration ensures all API routes, including error responses, return consistent CORS headers by importing and spreading the canonical header sets.
- Environment-driven policy allows operators to switch between wildcard and whitelist modes without code changes.
- Comprehensive testing in
tests/unit/cors/origins.test.tsand integration suites validates both the resolution logic and header propagation.
Frequently Asked Questions
How do I enable CORS for all origins in OmniRoute?
Set the environment variable CORS_ALLOW_ALL to a truthy value. According to the source code in src/server/cors/origins.ts, this enables echo mode, where the server returns the requesting origin's value in the Access-Control-Allow-Origin header, or falls back to wildcard * when no origin is present.
What environment variables control OmniRoute CORS behavior?
The system recognizes three variables: CORS_ALLOW_ALL (enables wildcard/echo mode), CORS_ALLOWED_ORIGINS (comma-separated whitelist), and CORS_ORIGIN (legacy single-origin fallback). The resolution logic in src/server/cors/origins.ts checks these in priority order to determine the final origin value.
How does OmniRoute handle pre-flight OPTIONS requests?
Route handlers export an OPTIONS function that calls handleCorsOptions() from src/shared/utils/cors.ts. This returns a 204 No Content response with the complete CORS_HEADERS set, satisfying browser pre-flight requirements without executing business logic.
Where are the CORS headers defined in the OmniRoute codebase?
The canonical header definitions reside in src/shared/utils/cors.ts, which exports CORS_HEADERS containing allowed methods and headers. The Access-Control-Allow-Origin value is resolved at runtime in src/server/cors/origins.ts and merged into the frozen STATIC_CORS_HEADERS object.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →