Skip to main content
This guide shows how to route AI requests through Lava’s gateway programmatically. Every request is logged with token counts, costs, and provider details automatically.
Start by choosing an auth path: Authenticate an Agent explains the difference between the MCP flow (lava_login inside the MCP) and the SDK flow (Lava.login() in your own code).
Managed vs unmanaged: You can use managed keys (Lava pays the provider; you pay Lava) or unmanaged (bring your own key — you supply the provider API key; Lava still meters usage and may charge a service fee). Both use the same forward token; set the optional provider_key in the token for unmanaged.

MCP flow

If your agent is using the Lava MCP server, do not reimplement this in code first. Use:
  • lava_login to authenticate the MCP session
  • lava_generate_forward_token for merchant-billed or customer-billed proxy auth
  • lava_chat_completions for the unified OpenAI-compatible endpoint
  • lava_messages for Anthropic-compatible requests
  • lava_forward for native provider passthrough, including non-LLM APIs
  • lava_rewrite for cross-provider request/response translation

SDK flow

If you are writing application code yourself, use the examples below with @lavapayments/nodejs.

How It Works

Lava’s gateway sits between your code and AI providers. You send requests to Lava’s forward URL instead of the provider’s URL directly. Lava proxies the request, tracks usage, and returns the provider’s response unchanged. The request body stays identical to what the provider expects. You only change the base URL and auth header.

Generate a Forward Token

A forward token encodes your credentials into a single auth header for proxied requests. The simplest forward token contains just your secret key — no customer or meter needed. Costs are charged to your merchant wallet directly.
import { Lava } from '@lavapayments/nodejs';

const lava = new Lava(); // reads LAVA_SECRET_KEY from env

// Secret-key-only forward token: charges your own wallet
const forwardToken = btoa(JSON.stringify({ secret_key: process.env.LAVA_SECRET_KEY }));
Find your secret key in Dashboard > Gateway > Secrets.
A secret-key-only forward token tracks usage against your own wallet without customer billing. To bill customers instead, see Bill Your Customers, which shows how to generate per-customer tokens with generateForwardToken().

Make a Request

Use the pre-configured provider URLs on the SDK. They point to Lava’s gateway with the correct upstream URL already set.
const response = await fetch(lava.providers.openai + '/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${forwardToken}`
  },
  body: JSON.stringify({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: 'Hello from my agent!' }]
  })
});

const data = await response.json();
console.log(data.choices[0].message.content);

Available Providers

The SDK includes pre-configured URLs for 25+ providers:
lava.providers.openai          // OpenAI
lava.providers.anthropic       // Anthropic
lava.providers.google          // Google (native)
lava.providers.googleOpenaiCompatible // Google (OpenAI-compatible)
lava.providers.mistral         // Mistral
lava.providers.deepseek        // DeepSeek
lava.providers.xai             // xAI (Grok)
lava.providers.groq            // Groq
lava.providers.together        // Together AI
lava.providers.fireworks       // Fireworks
lava.providers.cerebras        // Cerebras
// ... and more
See the full list of supported providers for all available options.

Discover Available Models

List all models available through the gateway:
const models = await lava.models.list();

for (const model of models.data) {
  console.log(`${model.id} (${model.owned_by})`);
}

Check Your Usage

After making requests, query your usage data:
// Get usage for the last 7 days
const usage = await lava.usage.retrieve({
  start: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
});

console.log('Total requests:', usage.totals.total_requests);
console.log('Total cost:', usage.totals.total_cost);

// List individual requests
const { data: requests } = await lava.requests.list({ limit: 5 });

for (const req of requests) {
  console.log(`${req.model} - ${req.model_usage.total_tokens} tokens - $${req.cost}`);
}

What’s Next?