Skip to main content

Overview

Connections represent the relationship between a customer’s wallet and your merchant account. Each connection has a unique connection_secret that you use to generate forward tokens for AI requests. After a customer completes checkout, a connection is automatically created. You can use the Connections resource to:
  • Retrieve connection details and wallet balance
  • List all connections for your merchant account
  • Filter connections by your internal reference ID
  • Delete connections to revoke access

Methods

list()

List all connections for your merchant account. Signature
list(params?: ConnectionsListParams): Promise<ListResponse<RestConnection>>
Parameters
NameTypeRequiredDescription
cursorstringNoPagination cursor for next page
limitnumberNoNumber of results per page (default: 10, max: 100)
reference_idstringNoFilter by your internal user/customer ID
Returns
{
  data: RestConnection[];
  has_more: boolean;
  next_cursor?: string;
}
Example: List All Connections
const connections = await lava.connections.list({
  limit: 50
});

for (const conn of connections.data) {
  console.log(`${conn.wallet.email}: $${conn.wallet.balance}`);
}
Example: Find Connection by Reference ID
const userConnections = await lava.connections.list({
  reference_id: 'user_123',
  limit: 1
});

if (userConnections.data.length > 0) {
  const connection = userConnections.data[0];
  console.log('Connection found:', connection.connection_id);
  console.log('Balance:', connection.wallet.balance);
} else {
  console.log('No connection found for this user');
}
Example: Pagination
let cursor: string | undefined;
const allConnections: RestConnection[] = [];

do {
  const response = await lava.connections.list({
    limit: 100,
    cursor
  });

  allConnections.push(...response.data);
  cursor = response.next_cursor;
} while (cursor);

console.log(`Total connections: ${allConnections.length}`);

retrieve()

Get detailed information for a specific connection. Signature
retrieve(connectionId: string): Promise<RestConnection>
Parameters
NameTypeRequiredDescription
connectionIdstringYesThe connection ID
Returns
{
  connection_id: string;
  connection_secret: string; // Use this to generate forward tokens
  reference_id?: string;
  wallet: {
    balance: string; // USD amount as decimal string
    phone: string;
    email: string;
    first_name: string;
    last_name: string;
    autopay_enabled: boolean;
  };
  next_usage_reset: string; // ISO 8601 timestamp
  previous_usage_reset: string;
  created_at: string;
}
Example: Check Wallet Balance
const connection = await lava.connections.retrieve('conn_abc123');

const balance = parseFloat(connection.wallet.balance);

if (balance < 1.00) {
  console.log('Low balance warning!');
  // Prompt user to add funds
} else {
  console.log(`Balance: $${balance.toFixed(2)}`);
}
Example: Get User Details
const connection = await lava.connections.retrieve('conn_abc123');

console.log('Customer:', connection.wallet.first_name, connection.wallet.last_name);
console.log('Email:', connection.wallet.email);
console.log('Phone:', connection.wallet.phone);
console.log('Autopay:', connection.wallet.autopay_enabled ? 'Enabled' : 'Disabled');

delete()

Delete a connection to revoke access. This prevents future AI requests using this connection’s forward tokens. Signature
delete(connectionId: string): Promise<{ success: boolean }>
Parameters
NameTypeRequiredDescription
connectionIdstringYesThe connection ID to delete
Returns
{
  success: boolean;
}
Example
const result = await lava.connections.delete('conn_abc123');

if (result.success) {
  console.log('Connection deleted successfully');
  // Remove connection_secret from your database
} else {
  console.error('Failed to delete connection');
}
Deleting a connection is permanent and cannot be undone. The customer’s wallet balance is preserved, but they will need to complete checkout again to create a new connection.

Common Use Cases

Pre-Request Balance Check

Verify sufficient balance before expensive operations:
async function checkBalanceBeforeRequest(connectionId: string, estimatedCost: number) {
  const connection = await lava.connections.retrieve(connectionId);
  const balance = parseFloat(connection.wallet.balance);

  if (balance < estimatedCost) {
    throw new Error(`Insufficient balance. Required: $${estimatedCost}, Available: $${balance}`);
  }

  return connection;
}

// Usage
try {
  await checkBalanceBeforeRequest('conn_abc123', 0.50);
  // Proceed with AI request
} catch (error) {
  // Prompt user to add funds
}

Balance Monitoring Dashboard

Display all customers and their balances:
async function getCustomerBalances() {
  const connections = await lava.connections.list({
    limit: 100
  });

  return connections.data.map(conn => ({
    userId: conn.reference_id,
    email: conn.wallet.email,
    balance: parseFloat(conn.wallet.balance),
    autopayEnabled: conn.wallet.autopay_enabled,
    lastReset: new Date(conn.previous_usage_reset)
  }));
}

// Usage
const customers = await getCustomerBalances();
const lowBalanceCustomers = customers.filter(c => c.balance < 5.00);
console.log(`${lowBalanceCustomers.length} customers with low balance`);

User Lookup by Email

Find a connection using the wallet email:
async function findConnectionByEmail(email: string) {
  let cursor: string | undefined;

  do {
    const response = await lava.connections.list({
      limit: 100,
      cursor
    });

    const match = response.data.find(conn =>
      conn.wallet.email.toLowerCase() === email.toLowerCase()
    );

    if (match) {
      return match;
    }

    cursor = response.next_cursor;
  } while (cursor);

  return null;
}

// Usage
const connection = await findConnectionByEmail('[email protected]');
if (connection) {
  console.log('Found connection:', connection.connection_id);
}

Revoking Access

Handle account deletion or subscription cancellations:
async function revokeUserAccess(userId: string) {
  // Find user's connection
  const connections = await lava.connections.list({
    reference_id: userId,
    limit: 1
  });

  if (connections.data.length === 0) {
    console.log('No connection found for user');
    return;
  }

  const connection = connections.data[0];

  // Delete the connection
  await lava.connections.delete(connection.connection_id);

  console.log(`Access revoked for user ${userId}`);

  // Clean up your database
  await database.users.update(userId, {
    lavaConnectionId: null,
    lavaConnectionSecret: null
  });
}

Auto-Topup Prompt

Prompt users when balance is low and autopay is disabled:
async function checkAndPromptTopup(connectionId: string) {
  const connection = await lava.connections.retrieve(connectionId);
  const balance = parseFloat(connection.wallet.balance);

  if (balance < 5.00 && !connection.wallet.autopay_enabled) {
    return {
      shouldPrompt: true,
      message: `Your balance is low ($${balance.toFixed(2)}). Add funds to continue.`,
      balance
    };
  }

  return {
    shouldPrompt: false,
    balance
  };
}

// Usage in your API
app.post('/api/chat', async (req, res) => {
  const topupCheck = await checkAndPromptTopup(req.user.connectionId);

  if (topupCheck.shouldPrompt) {
    return res.status(402).json({
      error: 'low_balance',
      message: topupCheck.message,
      balance: topupCheck.balance
    });
  }

  // Proceed with AI request
});

Understanding Connection Lifecycle

1. Connection Creation

Connections are created automatically when:
  • User completes onboarding checkout (new wallet created)
  • User completes subscription checkout (if no existing connection)
// After checkout webhook
const connection = await lava.connections.retrieve(webhookConnectionId);
console.log('New connection created:', connection.connection_id);

2. Active Connection

While active, you can:
  • Generate forward tokens for AI requests
  • Check wallet balance
  • Retrieve wallet and usage details
const token = lava.generateForwardToken({
  connection_secret: connection.connection_secret,
  product_secret: process.env.LAVA_PRODUCT_SECRET!
});

3. Connection Deletion

When deleted:
  • Forward tokens become invalid
  • No new AI requests can be made
  • Wallet balance is preserved
  • User can create a new connection via checkout
await lava.connections.delete(connection.connection_id);
// All forward tokens for this connection are now invalid

Webhook Integration

Listen for connection events via webhooks:
app.post('/webhooks/lava/connection-created', async (req, res) => {
  const { connection_id, reference_id } = req.body;

  // Store connection details
  const connection = await lava.connections.retrieve(connection_id);

  await database.users.update(reference_id, {
    lavaConnectionId: connection.connection_id,
    lavaConnectionSecret: connection.connection_secret,
    lavaWalletEmail: connection.wallet.email
  });

  res.json({ received: true });
});
Configure webhook endpoints in your Lava dashboard under Build > Webhooks.