How OmniRoute Handles CORS for API Routes: A Deep Dive into the Origins Module
OmniRoute centralizes all Cross-Origin Resource Sharing (CORS) logic in a single TypeScript module and applies it consistently through middleware, supporting both static environment configuration and dynamic runtime updates without server restarts.
The diegosouzapw/OmniRoute repository implements a security-first, fail-closed approach to CORS that prevents unauthorized cross-origin requests by default while offering flexible configuration options for production deployments. Understanding how OmniRoute handles CORS for API routes requires examining three key files that manage origin validation, header injection, and middleware orchestration.
Understanding the CORS Architecture in OmniRoute
Rather than scattering CORS headers throughout individual route handlers, OmniRoute consolidates all origin validation logic in src/server/cors/origins.ts. This centralized design ensures consistent security policy enforcement across every API endpoint, from public health checks to token-authenticated administrative routes.
The architecture follows a three-stage pipeline: origin definition, origin resolution, and header application. Each stage provides distinct hooks for environment-based configuration and runtime modification, allowing operators to update allow-lists without deploying new code.
The Core CORS Implementation in src/server/cors/origins.ts
The origins.ts module exports the primary functions that determine which origins may access API resources and how the server responds to cross-origin requests.
Defining the Allow-List via Environment and Runtime
OmniRoute constructs its CORS allow-list from multiple sources with clear precedence rules:
- Environment variables –
CORS_ALLOW_ALL(boolean switch),CORS_ALLOWED_ORIGINS(comma-separated list), and the legacyCORS_ORIGINstring provide static configuration at startup. - Runtime settings – The
setRuntimeAllowedOrigins()function updates the allow-list dynamically when the persistedcorsOriginssetting changes, enabling hot-reloading of origin policies.
All origins undergo normalization to ensure case-insensitive matching and removal of trailing slashes before comparison.
Origin Resolution with resolveAllowedOrigin()
The resolveAllowedOrigin(requestOrigin) function serves as the security gatekeeper. It returns the concrete value that should be echoed in the Access-Control-Allow-Origin header, or null if the origin is not permitted.
When CORS_ALLOW_ALL is set to true, the function returns the original request origin (or * when the Origin header is absent). In strict mode, it validates the request's Origin header against the merged allow-list containing both environment and runtime entries.
Header Application via applyCorsHeaders()
The applyCorsHeaders(response, request, relaxForTokenAuth?) function injects the complete set of CORS response headers:
Access-Control-Allow-Origin(only when an allowed origin is found)Vary: Origin(ensures caches vary by origin)Access-Control-Allow-MethodsandAccess-Control-Allow-Headers(standard allow-lists)- Echoed
access-control-request-headerswhen present in the request
The optional relaxForTokenAuth boolean parameter supports token-authenticated routes (such as /v1/* and /v1beta/*). When enabled and the origin fails standard validation, the function falls back to echoing the request origin or *. This relaxation is safe because token-authenticated endpoints never receive browser-attached credentials, eliminating the risk of reflected origin attacks.
Pre-Flight Handling and Middleware Integration
OmniRoute handles CORS at the middleware layer to eliminate the need for repetitive header logic in business code.
Static Headers in src/shared/utils/cors.ts
The src/shared/utils/cors.ts file exports CORS_HEADERS, a constant object containing baseline CORS headers used across the application. It also exposes handleCorsOptions(), a helper that responds to OPTIONS pre-flight requests with appropriate headers before the request reaches business logic handlers.
The Authorization Pipeline in src/server/authz/pipeline.ts
Every API route integrates with the middleware defined in src/server/authz/pipeline.ts, which automatically invokes applyCorsHeaders() for every response—including rejections, pre-flight OPTIONS requests, and normal payloads. This guarantees that CORS headers are present even on 401 Unauthorized or 403 Forbidden responses, preventing client-side fetch errors during authentication failures.
Special Handling for Token-Authenticated Routes
Token-authenticated endpoints in OmniRoute utilize the relaxForTokenAuth flag to support programmatic API access from arbitrary origins. Since these routes rely on bearer tokens rather than cookies or basic auth, the relaxed CORS behavior does not compromise security.
When relaxForTokenAuth is true, the middleware permits any origin to access the endpoint while still injecting the appropriate Access-Control-Allow-Origin header. This design pattern appears in the /v1/* and /v1beta/* route families, enabling third-party integrations without maintaining exhaustive origin allow-lists.
Practical Implementation Examples
Implementing CORS protection in a new OmniRoute endpoint requires minimal boilerplate when leveraging the existing pipeline:
// Standard route using the global CORS middleware
import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
export async function GET(request: Request) {
// Pre-flight handling (automatic in authz pipeline, shown here for clarity)
if (request.method === "OPTIONS") return handleCorsOptions(request);
const data = { hello: "world" };
return new Response(JSON.stringify(data), {
status: 200,
headers: { "Content-Type": "application/json", ...CORS_HEADERS },
});
}
For custom handlers outside the standard pipeline, apply CORS headers manually:
// Manual CORS application in a custom handler
import { applyCorsHeaders } from "@/server/cors/origins";
export async function handler(request: Request) {
const response = new Response("OK");
// relaxForTokenAuth = true for token-authenticated endpoints
applyCorsHeaders(response, request, true);
return response;
}
Summary
- OmniRoute implements a fail-closed CORS policy where no cross-origin requests are permitted unless explicitly configured via
CORS_ALLOWED_ORIGINSorCORS_ALLOW_ALL. - All origin validation logic lives in
src/server/cors/origins.ts, providing a single source of truth for security auditing. - The
applyCorsHeaders()function supports arelaxForTokenAuthmode that safely permits arbitrary origins for API token-authenticated routes. - Runtime origin updates via
setRuntimeAllowedOrigins()enable dynamic CORS policy changes without server restarts. - The authorization pipeline in
src/server/authz/pipeline.tsensures consistent CORS header injection across all response types, including errors and pre-flight requests.
Frequently Asked Questions
How do I configure allowed origins in OmniRoute?
Set the CORS_ALLOWED_ORIGINS environment variable to a comma-separated list of permitted origins (e.g., https://app.example.com,https://admin.example.com). For development environments, set CORS_ALLOW_ALL=true to permit any origin. Runtime updates are supported through the setRuntimeAllowedOrigins() function, which modifies the allow-list without requiring a server restart.
What is the difference between CORS_ALLOW_ALL and CORS_ALLOWED_ORIGINS?
CORS_ALLOW_ALL is a boolean flag that, when set to true, instructs OmniRoute to echo the request's Origin header back in the response (or return * when no Origin header is present), effectively allowing all cross-origin requests. CORS_ALLOWED_ORIGINS defines a specific allow-list of origins that undergo strict validation against the incoming Origin header. Production deployments should use CORS_ALLOWED_ORIGINS with CORS_ALLOW_ALL disabled to maintain security boundaries.
How does OmniRoute handle CORS pre-flight requests?
Pre-flight OPTIONS requests are handled by the handleCorsOptions() utility in src/shared/utils/cors.ts, which returns the appropriate CORS headers before the request reaches business logic. Additionally, the authorization pipeline in src/server/authz/pipeline.ts applies applyCorsHeaders() to all responses, ensuring that pre-flight requests receive consistent Access-Control-Allow-Methods and Access-Control-Allow-Headers headers regardless of the specific route implementation.
Can I update CORS origins without restarting the server?
Yes. OmniRoute supports runtime modification of the CORS allow-list through the setRuntimeAllowedOrigins() function exported from src/server/cors/origins.ts. When the persisted corsOrigins setting changes, calling this function updates the in-memory allow-list immediately. This capability enables dynamic CORS management through administrative interfaces or configuration webhooks without service interruption.
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 →