Skip to main content

What You’ll Build

In this quickstart, you’ll route your first AI request through Lava Build to track usage and costs. By the end, you’ll have:
  • A Lava forward token for authentication
  • A working API call routed through Lava’s proxy
  • Usage data visible in your dashboard
Prerequisites: You need a Lava account and a backend server. Lava requires backend integration—direct frontend calls are blocked by CORS for security.

Step 1: Find Your Token

Your self forward token is auto-generated when you sign up. This token authenticates your requests and links them to your account for usage tracking.
1

Navigate to Secret Keys

Go to Build > Secret Keys in your dashboard.
2

Copy Your Token

Find the “Self Forward Token” section and click the copy icon to copy your token to clipboard.
What makes this token “self”? It’s automatically configured to charge your own wallet, making it perfect for testing and personal projects. No additional setup required.

Step 2: Set Up Your Project

Create a .env.local file in your project root with these variables:
.env.local
LAVA_FORWARD_TOKEN=your_copied_token_here
LAVA_BASE_URL=https://api.lavapayments.com/v1
About the API URL: You’ll construct the full endpoint by appending /forward?u=<provider_url> to the base URL. The u parameter tells Lava which AI provider to route your request to.Example for OpenAI: ${LAVA_BASE_URL}/forward?u=https://api.openai.com/v1/chat/completions
Where this file goes: Place .env.local at the root of your project (same level as package.json). Most frameworks (Next.js, Vite, Create React App) automatically load environment variables from this file. Add .env.local to your .gitignore to keep tokens secure.

Step 3: Understanding the Request URL

Let’s break down how Lava routes your request. The URL has three parts:
https://api.lavapayments.com/v1/forward?u=https://api.openai.com/v1/chat/completions
Breaking it down:
PartValuePurpose
Base URLhttps://api.lavapayments.com/v1Lava’s API endpoint (from your .env.local)
Forward path/forwardTells Lava to route the request
Query parameter?u=https://api.openai.com/v1/chat/completionsSpecifies which AI provider to call
Lava reads the ?u= parameter and routes your request to that endpoint. For this tutorial, we’re routing to OpenAI’s chat completions endpoint.

Step 4: Add Authentication

The forward token authenticates your request and links it to your account for usage tracking:
// Headers for the request
const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${process.env.LAVA_FORWARD_TOKEN}`
};
The Authorization header tells Lava which account to charge for this request.

Step 5: Define the Request Body

The request body is sent directly to OpenAI. It uses OpenAI’s standard format—no modifications needed:
// Standard OpenAI request format
const requestBody = {
  model: 'gpt-4o-mini',
  messages: [
    { role: 'user', content: 'Say hello in one sentence.' }
  ]
};
Lava passes this through unchanged to OpenAI. You use the provider’s native API format.

Step 6: Make the Request

Now let’s put it all together. Create a file called test-lava.js:
test-lava.js
// Load environment variables
require('dotenv').config({ path: '.env.local' });

async function testLava() {
  // 1. Build the URL - routes to OpenAI via Lava
  const url = `${process.env.LAVA_BASE_URL}/forward?u=https://api.openai.com/v1/chat/completions`;

  // 2. Set up authentication
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.LAVA_FORWARD_TOKEN}`
  };

  // 3. Define the request body (standard OpenAI format)
  const requestBody = {
    model: 'gpt-4o-mini',
    messages: [
      { role: 'user', content: 'Say hello in one sentence.' }
    ]
  };

  // 4. Make the request
  const response = await fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(requestBody)
  });

  // 5. Parse and log the response
  const data = await response.json();
  console.log('\nResponse from OpenAI:');
  console.log(JSON.stringify(data, null, 2));

  // 6. Show the Lava request ID for tracking
  const requestId = response.headers.get('x-lava-request-id');
  console.log('\nLava request ID:', requestId);
}

testLava();
Run it:
node test-lava.js

Step 7: See the Results

You should see output like this:
Response from OpenAI:
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-4o-mini",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you today?"
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 13,
    "completion_tokens": 8,
    "total_tokens": 21
  }
}

Lava request ID: req_abc123...
The response format is identical to calling OpenAI directly—Lava doesn’t modify it.

Step 8: Check the Dashboard

Lava automatically tracked usage and costs for your request. Let’s see what data is available:
  1. Go to Monetize > Explore in your dashboard
  2. Find your request using the timestamp or request ID
  3. View the details Lava captured:
    • Token counts: Input (13), output (8), total (21)
    • Cost breakdown: Base cost charged to your wallet
    • Model: gpt-4o-mini
    • Provider: OpenAI
The x-lava-request-id header connects the console output to the dashboard logs—useful for debugging and analytics.

Step 9: Use in Your Application (Optional)

Once you’ve confirmed the test request works, you can add the same code to your application. Here’s the same request wrapped in a Next.js API route:
app/api/chat/route.ts
export async function POST(request: Request) {
  const body = await request.json();

  // Same request from test-lava.js, just wrapped in Next.js
  const response = await fetch(
    `${process.env.LAVA_BASE_URL}/forward?u=https://api.openai.com/v1/chat/completions`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.LAVA_FORWARD_TOKEN}`
      },
      body: JSON.stringify(body)
    }
  );

  return response;
}
Why backend only? Forward tokens contain credentials that charge your wallet. Lava blocks frontend requests with CORS to prevent token exposure and unauthorized charges.
See the Forward Proxy Guide for advanced configuration, streaming, and multi-provider patterns.

What’s Next?

Ready to monetize? Once you’re comfortable with Build, see the Monetize Quickstart to configure pricing and charge customers.

How Lava Build Works

Lava acts as a transparent proxy between your application and AI providers:
  1. Your app sends a request with the forward token
  2. Lava validates the token and checks wallet balance
  3. Request is forwarded to the upstream provider (OpenAI, Anthropic, etc.)
  4. Usage is metered automatically based on provider response
  5. Costs are charged to your Lava wallet using prepaid credits
Lava adds less than 20ms of latency through edge computing and Redis caching. Streaming responses work seamlessly.

Troubleshooting

See Step 1: Get Your Forward Token above for the exact location.If you don’t see it in your dashboard:
  • Verify you’re logged into your merchant account (not a wallet-only account)
  • Check that your account setup completed successfully
  • Contact [email protected] if the Test Your Setup section is missing
Cause: Invalid or missing forward tokenSolution:
  • Verify you copied the complete token from the dashboard
  • Check that the token is properly base64-encoded if you created it manually
  • Ensure the Authorization: Bearer header is included
Cause: Your Lava wallet doesn’t have enough creditsSolution:
  • Navigate to Wallet > Billing in the dashboard
  • Add a payment method and fund your wallet
  • Enable autopay to automatically top up when balance runs low
Cause: Attempted to call Lava from client-side JavaScriptSolution:
  • Move the API call to your backend server
  • Lava blocks frontend requests for security (prevents token exposure)
Cause: Request may have failed before reaching Lava, or you’re looking at the wrong time rangeSolution:
  • Check your application logs for errors
  • Verify the request actually executed
  • Adjust the time range filter in the dashboard
  • Look for error responses in the HTTP status code
Secret key: Your base API credential (like a username/password). Managed in the Secrets page.Forward token: A composite credential that includes your secret key + connection ID + product ID. This is what you actually use in API calls.Self forward token: A special forward token that charges your own Lava wallet. Perfect for development and testing. Generated automatically using your “Default” secret key.For production apps: You’ll generate custom forward tokens programmatically for each customer using the @lavapayments/nodejs SDK. See Monetize Quickstart.
Yes, but most developers only need the auto-generated “Default” key.When to create additional keys:
  • Separating dev/staging/prod environments
  • Security rotation best practices
  • Different team members or projects
How to create: Navigate to Build > Secrets and click ”+ Create Secret Key”Note: Additional keys require manual forward token generation using the SDK. See SDK Reference for details.

Understanding Authentication

The Relationship Between Secret Keys and Forward Tokens

Lava uses a two-layer authentication system: Layer 1: Secret Keys
  • Base credentials you manage in your dashboard
  • Used to prove you’re an authorized merchant
  • Can be rotated for security
  • Never sent directly in API calls
Layer 2: Forward Tokens
  • Composite credentials combining: secret key + connection + product
  • What you actually send in the Authorization header
  • Generated programmatically (except self forward token)
  • Each customer gets their own forward token
Why this architecture? This separation allows flexible billing. The same secret key can generate many different forward tokens—each connecting a different customer wallet to different pricing products. You maintain one secret key, but serve many customers with custom billing.

Self Forward Token: A Special Case

The self forward token is unique:
  • ✅ Auto-generated on signup (no SDK needed)
  • ✅ Uses your “Default” secret key automatically
  • ✅ Charges your own merchant wallet (not a customer’s)
  • ✅ Perfect for development and testing
For production apps with customer billing, you’ll use the SDK to generate forward tokens dynamically. See Monetize Quickstart.

Support

Having trouble? We’re here to help: