import { useLayercodeAgent } from "@layercode/react";

// Connect to a Layercode agent
const {
  // Methods
  triggerUserTurnStarted,
  triggerUserTurnFinished,

  // State
  status,
  userAudioAmplitude,
  agentAudioAmplitude,
} = useLayercodeAgent({
  agentId: "your-agent-id",
  authorizeSessionEndpoint: "/api/authorize",
  conversationId: "optional-conversation-id", // optional
  metadata: { userId: "user-123" }, // optional
  onConnect: ({ conversationId }) => console.log("Connected to agent", conversationId),
  onDisconnect: () => console.log("Disconnected from agent"),
  onError: (error) => console.error("Agent error:", error),
  onDataMessage: (data) => console.log("Received data:", data),
});
layercode-react-sdk.

useLayercodeAgent Hook

The useLayercodeAgent hook provides a simple way to connect your React app to a Layercode agent, handling audio streaming, playback, and real-time communication.
import { useLayercodeAgent } from "@layercode/react";

// Connect to a Layercode agent
const {
  // Methods
  triggerUserTurnStarted,
  triggerUserTurnFinished,

  // State
  status,
  userAudioAmplitude,
  agentAudioAmplitude,
} = useLayercodeAgent({
  agentId: "your-agent-id",
  authorizeSessionEndpoint: "/api/authorize",
  conversationId: "optional-conversation-id", // optional
  metadata: { userId: "user-123" }, // optional
  onConnect: ({ conversationId }) => console.log("Connected to agent", conversationId),
  onDisconnect: () => console.log("Disconnected from agent"),
  onError: (error) => console.error("Agent error:", error),
  onDataMessage: (data) => console.log("Received data:", data),
});

Hook Options

agentId
string
required
The ID of your Layercode agent.
authorizeSessionEndpoint
string
required
The endpoint to authorize the session (should return a client_session_key and session_id). Note: From Mon Sep 1, 12:00 UTC, the response will include conversation_id instead of session_id (see REST API page).
conversationId
string
The conversation ID to resume a previous conversation (optional).
metadata
object
Any metadata included here will be passed along to your backend with all webhooks.
onConnect
function
Callback when the connection is established. Receives an object: { conversationId: string | null }.
onDisconnect
function
Callback when the connection is closed.
onError
function
Callback when an error occurs. Receives an Error object.
onDataMessage
function
Callback for custom data messages from the server (see response.data events from your backend).

Return Values

The useLayercodeAgent hook returns an object with the following properties:

State

status
string
The connection status. One of "initializing", "disconnected", "connecting", "connected", or "error".
userAudioAmplitude
number
Real-time amplitude of the user’s microphone input (0-1). Useful for animating UI when the user is speaking.
agentAudioAmplitude
number
Real-time amplitude of the agent’s audio output (0-1). Useful for animating UI when the agent is speaking.

Turn-taking (Push-to-Talk)

Layercode supports both automatic and push-to-talk turn-taking. For push-to-talk, use these methods to signal when the user starts and stops speaking:
triggerUserTurnStarted
function
triggerUserTurnStarted(): void Signals that the user has started speaking (for push-to-talk mode). Interrupts any agent audio playback.
triggerUserTurnFinished
function
triggerUserTurnFinished(): void Signals that the user has finished speaking (for push-to-talk mode).

Notes & Best Practices

  • The hook manages microphone access, audio streaming, and playback automatically.
  • The metadata option allows you to set custom data which is then passed to your backend webhook (useful for user/session tracking).
  • The conversationId can be used to resume a previous conversation, or omitted to start a new one.

Authorizing Sessions

To connect a client (browser) to your Layercode voice agent, you must first authorize the session. The SDK will automatically send a POST request to the path (or url if your backend is on a different domain) passed in the authorizeSessionEndpoint option. In this endpoint, you will need to call the Layercode REST API to generate a client_session_key and conversation_id (if it’s a new conversation).
If your backend is on a different domain, set authorizeSessionEndpoint to the full URL (e.g., https://your-backend.com/api/authorize).
Why is this required? Your Layercode API key should never be exposed to the frontend. Instead, your backend acts as a secure proxy: it receives the frontend’s request, then calls the Layercode authorization API using your secret API key, and finally returns the client_session_key to the frontend. This also allows you to authenticate your user, and set any additional metadata that you want passed to your backend webhook. How it works:
  1. Frontend: The SDK automatically sends a POST request to your authorizeSessionEndpoint with a request body.
  2. Your Backend: Your backend receives this request, then makes a POST request to the Layercode REST API /v1/agents/web/authorize_session endpoint, including your LAYERCODE_API_KEY as a Bearer token in the headers.
  3. Layercode: Layercode responds with a client_session_key (and a conversation_id), which your backend returns to the frontend.
  4. Frontend: The SDK uses the client_session_key to establish a secure WebSocket connection to Layercode.
Example backend authorization endpoint code:
export const dynamic = "force-dynamic";
import { NextResponse } from "next/server";

export const POST = async (request: Request) => {
  // Here you could do any user authorization checks you need for your app
  const endpoint = "https://api.layercode.com/v1/agents/web/authorize_session";
  const apiKey = process.env.LAYERCODE_API_KEY;
  if (!apiKey) {
    throw new Error("LAYERCODE_API_KEY is not set.");
  }
  const requestBody = await request.json();
  if (!requestBody || !requestBody.agent_id) {
    throw new Error("Missing agent_id in request body.");
  }
  try {
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify(requestBody),
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(text || response.statusText);
    }
    return NextResponse.json(await response.json());
  } catch (error: any) {
    console.log("Layercode authorize session response error:", error.message);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
};
For a Python backend example see the FastAPI backend guide.