This example demonstrates how to route Anam AI SDK traffic through your own API Gateway server.
anam-gateway-example/
├── gateway-server/
│ ├── server.js # Gateway server (HTTP + WebSocket)
│ └── package.json
├── src/
│ ├── app/
│ │ ├── api/session-token/ # Secure session token generation
│ │ └── page.tsx
│ └── components/
│ └── AnamPlayer.tsx # SDK integration with gateway config
└── .env.local
This example shows how to configure the Anam SDK to route all HTTP and WebSocket requests through an intermediary gateway server instead of connecting directly to Anam's infrastructure. This is useful for:
- Adding custom authentication or authorization
- Logging and monitoring API calls
- Rate limiting or request filtering
- Complying with security policies requiring backend-only external API access
# Install frontend dependencies
pnpm i
# Install gateway server dependencies
cd gateway-server
pnpm i
cd ..Create .env.local in the root directory:
ANAM_API_KEY=your_api_key_here
NEXT_PUBLIC_ENABLE_GATEWAY=true
NEXT_PUBLIC_GATEWAY_URL=http://localhost:3001# Terminal 1 - Start gateway server
cd gateway-server
npm start
# Terminal 2 - Start frontend
npm run devNavigate to http://localhost:3000 and start a chat session.
The Anam SDK accepts custom gateway configuration which can be passed in when creating the Anam client:
const clientOptions = {
api: {
apiGateway: {
enabled: true,
baseUrl: 'http://localhost:3001',
wsPath: '/ws'
}
}
};
await startChat(sessionToken, clientOptions);The SDK will route all http and websocket requests through your gateway server instead of connecting directly to Anam.
Note: WebRTC traffic still connects using a direct peer-to-peer connection. This is a core part of the WebRTC protocol and it's optimised to find the best path.
The gateway server handles two types of requests:
The SDK sends the complete target URL via the X-Anam-Target-Url header. The gateway extracts this header and forwards the request to the target.
Client → Gateway → Anam API (or Engine) → Gateway → Client
The SDK includes the complete target WebSocket URL as a target_url query parameter. The gateway:
- Extracts the
target_urlparameter - Establishes a connection to the target before accepting the client connection
- Forwards messages bidirectionally between client and target
- Converts messages to text frames for proper signaling
Client WebSocket → Gateway WebSocket → Target WebSocket
In this example we've made the gateway using a simple express server. However the same result could be achieved using any preferred framework that is capable of proxying http and websocket traffic using dynamic tartget urls (the target urls change and are unique to each session). This could include nginx, traefik, HAProxy, etc.