How OmniRoute Implements Optional Authentication for API Requests

OmniRoute implements optional authentication through a toggleable environment variable (REQUIRE_API_KEY) that controls a three-step pipeline: credential extraction, SQLite-backed validation, and conditional enforcement across all API routes.

OmniRoute provides a flexible, open-source API routing layer that supports both public and authenticated access modes through a single environment configuration. By setting the REQUIRE_API_KEY flag, operators can instantly enforce API key validation on all endpoints without modifying individual route logic.

The Three-Step Authentication Pipeline

OmniRoute’s authentication system follows a consistent pattern implemented in src/sse/services/auth.ts and src/shared/utils/clientApiRouteAuth.ts. Every request passes through extraction, validation, and enforcement stages.

Extracting Credentials from Headers and Query Parameters

The extractApiKey function parses incoming requests for credentials in two locations. It first checks the Authorization header for a Bearer token, then falls back to an api-key query parameter. This dual-source approach ensures compatibility with both standard HTTP clients and simple GET requests.

Validating Keys Against the SQLite Store

Extracted keys are verified via the isValidApiKey function, which queries the api_keys table in the application's SQLite database. This function returns a boolean indicating whether the key exists and is active, providing the boolean gate for subsequent authorization logic.

Enforcing Optional Authentication via Environment Flags

The enforceClientApiRouteAuth function in src/shared/utils/clientApiRouteAuth.ts orchestrates the optional behavior. Internally, it calls isRequireApiKeyEnabled() to read the REQUIRE_API_KEY environment variable. When this flag is false or unset, the function immediately returns null and the request proceeds unsecured. When true, the function requires a valid API key via isValidApiKey, returning a 401 Unauthorized response if the key is missing or invalid.

Implementation Patterns in API Routes

Concrete API endpoints consume these utilities through two primary patterns, ensuring a uniform security posture without code duplication.

Inline Authentication in Chat Completions

The chat completions endpoint at src/app/api/v1/chat/completions/route.ts imports extractApiKey and isValidApiKey directly from the auth service. It performs the optional check inline, allowing fine-grained control over the authentication flow for streaming responses.

Delegated Enforcement in Image Generation

The image generation route at src/app/api/v1/images/generations/route.ts delegates entirely to enforceClientApiRouteAuth. This approach centralizes the decision logic, making the route handler cleaner and ensuring consistent 401 responses across all unauthenticated requests when the feature flag is enabled.

Provider-Specific Embeddings Endpoints

Dynamic provider routes such as src/app/api/v1/providers/[provider]/embeddings/route.ts also leverage the shared enforceClientApiRouteAuth helper. This ensures that third-party provider proxies inherit the same optional authentication behavior without redundant implementation.

Configuration and Deployment Modes

The optional authentication system allows seamless transitions between development and production environments.

Development Mode: Running Without Authentication

When REQUIRE_API_KEY is unset or set to false, OmniRoute accepts all requests regardless of headers. This configuration is ideal for local testing and internal networks.

// No API key required – request succeeds because REQUIRE_API_KEY is false
await fetch('http://localhost:20128/v1/chat/completions', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ 
    model: 'gpt-4o-mini', 
    messages: [{ role: 'user', content: 'Hello' }] 
  })
});

Production Mode: Enforcing Strict Key Validation

Setting REQUIRE_API_KEY=true activates strict validation. Requests must include a valid key in the Authorization header or query string, or the server responds with 401 Unauthorized.

// Production request with valid Bearer token
await fetch('https://api.omniroute.com/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer sk-prod-1234567890abcdef'
  },
  body: JSON.stringify({ 
    model: 'gpt-4o-mini', 
    messages: [{ role: 'user', content: 'Hello' }] 
  })
});

Programmatic Enforcement in Custom Routes

Developers building custom endpoints can reuse the enforcement logic directly:

import { enforceClientApiRouteAuth } from '@/shared/utils/clientApiRouteAuth';

export async function GET(request: Request) {
  const authRejection = await enforceClientApiRouteAuth(request);
  if (authRejection) return authRejection; // Returns 401 if auth enabled and invalid
  
  return new Response(JSON.stringify({ status: 'ok' }), { status: 200 });
}

Summary

  • OmniRoute uses the REQUIRE_API_KEY environment variable as a single toggle to enable or disable API authentication globally.
  • The pipeline relies on three core functions: extractApiKey for parsing credentials, isValidApiKey for database verification, and enforceClientApiRouteAuth for conditional enforcement.
  • Authentication logic is centralized in src/sse/services/auth.ts and src/shared/utils/clientApiRouteAuth.ts, ensuring DRY principles.
  • API routes implement the check either inline (as in chat completions) or via delegation (as in image generation).
  • Valid API keys are stored and verified against the SQLite api_keys table.

Frequently Asked Questions

How do I disable API authentication in OmniRoute for local testing?

Unset the REQUIRE_API_KEY environment variable or set it to false. When disabled, enforceClientApiRouteAuth bypasses validation entirely, allowing all requests to proceed without credentials. This is the default behavior in development environments.

What database table stores the API keys?

OmniRoute stores valid credentials in the api_keys table within its SQLite database. The isValidApiKey function performs a lookup against this table to verify that a provided key exists and is active before granting access.

Can I use query parameters instead of headers to pass the API key?

Yes, the extractApiKey utility in src/sse/services/auth.ts supports both methods. It first inspects the Authorization header for a Bearer token, then checks for an api-key query parameter, allowing flexibility for different client implementations.

What HTTP status code does OmniRoute return for missing or invalid keys?

When REQUIRE_API_KEY is enabled and a request lacks a valid key, the server returns 401 Unauthorized. This response is generated by enforceClientApiRouteAuth when isValidApiKey returns false or no credentials are detected.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →