# How OmniRoute Handles CORS Requests: A Complete Technical Guide

> Discover how OmniRoute handles CORS requests with its centralized, declarative strategy using static headers and dynamic origin resolution. Learn about environment-driven configuration for consistent cross-origin handling.

- Repository: [Diego Rodrigues de Sa e Souza/OmniRoute](https://github.com/diegosouzapw/OmniRoute)
- Tags: how-to-guide
- Published: 2026-08-28

---

**OmniRoute implements a centralized, declarative CORS strategy through static headers defined in [`src/shared/utils/cors.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/shared/utils/cors.ts) and dynamic origin resolution managed by [`src/server/cors/origins.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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:

```typescript
// 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:

```typescript
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:

```typescript
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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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 any `Origin` header** (allow-all mode)
- **`CORS_ALLOWED_ORIGINS`** – Comma-separated whitelist of explicit origins
- **`CORS_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:

```typescript
// 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:

```typescript
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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/shared/utils/cors.ts) provides the `CORS_HEADERS` constant and `handleCorsOptions()` helper used by every route.
- **Dynamic origin resolution** in [`src/server/cors/origins.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/server/cors/origins.ts) evaluates `CORS_ALLOW_ALL`, `CORS_ALLOWED_ORIGINS`, and `CORS_ORIGIN` to set the correct `Access-Control-Allow-Origin` value.
- **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.ts`](https://github.com/diegosouzapw/OmniRoute/blob/main/tests/unit/cors/origins.test.ts) and 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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/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`](https://github.com/diegosouzapw/OmniRoute/blob/main/src/server/cors/origins.ts) and merged into the frozen `STATIC_CORS_HEADERS` object.