Features
- Request/Response Hooks - Transform requests and responses with
beforeRequest,afterResponse, andonErrorhooks - Streaming Support - Full SSE streaming with content aggregation using AI SDK V3 protocol
- Framework Agnostic - Works with Next.js, Hono, Express, and other frameworks
Installation
Usage
Next.js App Router
Create a catch-all route handler atapp/api/ai/[...segments]/route.ts:
Custom Catch-All Parameter Name
If your route uses a different parameter name (e.g.,app/api/ai/[...path]/route.ts):
Hono
For frameworks without catch-all route support, use theextractPath option:
Express / Node.js
Configuration
Custom Base URL
Additional Headers
Request Transformation
Transform the request body before forwarding to the gateway:Response Transformation
Transform the response after receiving from the gateway. For streaming responses, this is called when the stream completes with aggregated content:Error Handling
Custom error handling with theonError hook:
Authentication
The proxy automatically handles authentication using one of the following methods (in order of priority):API Key
Set theAI_GATEWAY_API_KEY environment variable:
OIDC (Vercel)
When deployed on Vercel, the proxy automatically uses Vercel OIDC for authentication. No additional configuration is required.API Reference
createGatewayProxy(options?)
Creates a proxy handler for the AI Gateway.
Options
| Option | Type | Default | Description |
|---|---|---|---|
baseUrl | string | "https://ai-gateway.vercel.sh/v1/ai" | The base URL of the AI Gateway |
headers | Record<string, string> | {} | Additional headers to include in requests |
segmentsParam | string | "segments" | The name of the catch-all parameter in the route |
extractPath | (request: Request) => string | Promise<string> | - | Custom function to extract the path from the request. When provided, segmentsParam is ignored |
beforeRequest | (ctx) => request | - | Transform request body before forwarding |
afterResponse | (ctx) => response | - | Transform response after receiving (aggregated for streaming) |
onError | (ctx) => error | Response | - | Custom error handling |
Returns
A handler function with named exports for HTTP methods:GET, POST, PUT, DELETE, PATCH.
getGatewayAuthToken()
Retrieves the authentication token for the AI Gateway.
StreamContentAggregator
Aggregates streaming content into a complete response. Used internally by the proxy for afterResponse hooks on streaming requests.
createStreamTransformer(body, requestBody, afterResponse)
Creates a transform stream that passes through SSE events while aggregating content and calling the afterResponse hook on completion.