any webhooks are available in livekit to track th...
# ask-ai
a
any webhooks are available in livekit to track the session creation and session completion
t
Thanks for reaching out, Vanaja. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking if LiveKit provides webhooks to track session creation and completion — yes. • Use room_started to detect when a room/session is created (first participant joins). • Use room_finished to detect when a room/session ends (last participant leaves). To receive these: 1. LiveKit Cloud: enable webhooks in the project dashboard under Settings. 2. Self-hosted: add a
webhook
section to your server
config.yaml
with your endpoint(s) and API key:
Copy code
webhook:
  api_key: 'your-api-key'
  urls:
    - 'https://your-webhook-endpoint.com'
Delivery and security: • Webhook requests include a JWT in the
Authorization
header for integrity (SHA-256 hash of payload). • LiveKit retries and queues events for reliable delivery. If you want, I can: • show example payloads for
room_started
and
room_finished
, or • walk through validating the webhook JWT in your preferred language (Node/Go/Java). Which would help most? Sources: Webhook & Event System | livekit/livekit_composite | DeepWiki | Webhooks | LiveKit docs | server-sdk-ruby | livekit/livekit_composite | DeepWiki | server-sdk-js | livekit/livekit_composite | DeepWiki
a
• show example payloads for
room_started
and
room_finished
, or • walk through validating the webhook JWT in your preferred language in node .
t
Responding to your request for example payloads for
room_started
/
room_finished
and a Node.js walkthrough to validate the webhook JWT. Example payloads • room_started
Copy code
{
  "event": "room_started",
  "room": {
    "sid": "RM_1234567890",
    "name": "my-room",
    "empty_timeout": 300,
    "max_participants": 10,
    "creation_time": 1648713600
  },
  "id": "evt_1234567890",
  "createdAt": 1648713600
}
• room_finished
Copy code
{
  "event": "room_finished",
  "room": {
    "sid": "RM_1234567890",
    "name": "my-room",
    "empty_timeout": 300,
    "max_participants": 10,
    "creation_time": 1648713600
  },
  "id": "evt_0987654321",
  "createdAt": 1648717200
}
Validating the webhook JWT in Node.js 1. Install the LiveKit server SDK: • npm install livekit-server-sdk 1. Use
express.raw()
to preserve the raw body and validate with `WebhookReceiver`:
Copy code
const express = require('express');
const { WebhookReceiver } = require('livekit-server-sdk');

const app = express();
const receiver = new WebhookReceiver('YOUR_API_KEY', 'YOUR_API_SECRET');

app.post(
  '/webhook-endpoint',
  express.raw({ type: 'application/webhook+json' }),
  async (req, res) => {
    try {
      const authHeader = req.get('Authorization') || '';
      const event = await receiver.receive(req.body, authHeader);

      // handle events
      if (event.event === 'room_started') {
        console.log('Room started:', event.room.name);
      } else if (event.event === 'room_finished') {
        console.log('Room finished:', event.room.name);
      }

      res.status(200).send('OK');
    } catch (err) {
      console.error('Webhook validation failed:', err);
      res.status(401).send('Unauthorized');
    }
  }
);

app.listen(3000);
Notes: • Use content type
application/webhook+json
so Express raw middleware runs. •
WebhookReceiver.receive()
verifies the JWT signature, timestamp, and payload hash using your API secret. • Log and respond quickly; return 200 for successful processing so LiveKit won't retry. Would you like a complete example using TypeScript or help testing the endpoint locally? Sources: Webhooks | LiveKit docs
a
can we get agent type in any hook ? which we define during agent dispatch
t
You're asking whether a dispatch-defined "agent type" can appear in LiveKit webhooks — it isn't included natively, but you can surface it. Options you can use: • Set the agent type in room metadata when the agent starts (or update
room.metadata
).
room_started
and other room-level webhooks include room metadata. • Set the agent type in participant metadata/attributes when the agent connects.
participant_joined
and participant-related webhooks include participant metadata. • Have the agent write its
agent_type
from its JobContext into room/participant metadata at startup so your backend can read it from incoming webhooks. If you want, I can: • show exactly where
agent_type
appears in a
room_started
or
participant_joined
payload, or • give a Node.js example of updating room/participant metadata from the agent so it appears in webhooks. Which would you prefer? Sources: Webhooks | LiveKit docs | Agent dispatch | LiveKit docs | Events and error handling | LiveKit docs | Participant attributes and metadata | LiveKit docs | Egress API | LiveKit docs
a
can we add room metadata here token.roomConfig = new RoomConfiguration({ agents: [ new RoomAgentDispatch({ agentName, metadata: JSON.stringify(options || {}), }), ], }); similar to this const room = await liveKitService.createOrGetRoom(roomName, { metadata: { agent_type: agentName, // Use agent_type key for clarity ...metadata } });
t
You're on the right track —
token.roomConfig = new RoomConfiguration(...)
(the token's room config / agent dispatch metadata) does not set the room's persistent
room.metadata
. Metadata passed to an agent dispatch is separate and lives in the agent's JobContext; it won't automatically appear in webhook
room
fields. Do this instead: • Create or get the room (as you already do). • Update the room's metadata to include
agent_type
(and any other fields you want present in webhooks). • The room metadata will then appear in
room_started
,
participant_joined
, and other room-level webhook payloads. Example Node.js flow:
Copy code
// 1) create/get room (your existing code)
const room = await liveKitService.createOrGetRoom(roomName, {
  metadata: {
    agent_type: agentName,
    ...metadata,
  },
});

// 2) issue token for agent with dispatch metadata (optional)
token.roomConfig = new RoomConfiguration({
  agents: [
    new RoomAgentDispatch({
      agentName,
      metadata: JSON.stringify(options || {}),
    }),
  ],
});

// 3) (if needed) update room metadata later via server SDK / REST
await liveKitService.updateRoom(roomName, {
  metadata: {
    agent_type: agentName,
    ...metadata,
  },
});
Notes and best practices • Put
agent_type
in
room.metadata
if you want it in webhooks like
room_started
/
room_finished
. • Keep agent-specific runtime data in the dispatch metadata or participant metadata if it's per-agent rather than per-room. • If the agent writes participant metadata on connect, that will appear in participant-related webhooks too. Would you like a concrete example of updating room metadata via the LiveKit REST/SDK method you use (Node.js snippet for your liveKitService)?
a
later room configuration am updating the room with meta data but am not getting in event data under room_started and room_finished events only able to see with this code snippet const room = await liveKitService.createOrGetRoom(roomName, { metadata: { agent_type: agentName, ...metadata, }, });
t
You mentioned updating room metadata after creation but only the metadata set during create appears in
room_started
/
room_finished
. I can help troubleshoot—here’s what's happening and how to make updates surface in webhooks. Why this happens • The
room_started
event is emitted when the room is first created / first participant joins; it captures the room state at that moment. If you update room metadata after that event is emitted, the earlier
room_started
payload won’t change. •
room_finished
is emitted when the room closes; it will include the room state at the time
room_finished
is generated. If you update metadata too late (after the last participant leaves but before the server constructs the
room_finished
event), it may not be included. What to do • Set the
agent_type
on the room before the room is started (before the first participant connects). Your create-or-get call that includes metadata is the most reliable way: ◦ const room = await liveKitService.createOrGetRoom(roomName, { metadata: { agent_type: agentName, ...metadata } }); • If you must update metadata after creation, update it early—before any participants join—so
room_started
sees it. • To ensure
room_finished
contains the latest metadata, update room metadata while participants remain in the room (so the server has the updated state when the last participant leaves). Debug checklist • Confirm you’re calling the LiveKit API/SDK method that persists
room.metadata
(not just a local variable). • Verify the update request succeeds (200/OK) and
room.metadata
shows the new value when you fetch the room immediately after update. • Ensure timing: update happens before the event is emitted (before first join for `room_started`; while room is active for
room_finished
). If you want, I can: • provide a Node.js snippet to update room metadata and verify it (including fetch-after-update), or • help you add participant metadata as an alternative so participant-related webhooks include
agent_type
. Which would you prefer?
a
this is the code i have to configure room and agent dispatch , here where can i add room metadata generateAccessTokenWithAgentDispatch(roomName, participantName, participantIdentity, agentName, options = {}) { const token = new AccessToken( this.config.apiKey, this.config.apiSecret, { identity: participantIdentity, name: participantName } ); token.addGrant({ room: roomName, roomJoin: true, canPublish: options.canPublish !== false, canSubscribe: options.canSubscribe !== false, canPublishData: options.canPublishData !== false }); options.participantName = participantName; options.participantIdentity = participantIdentity; // Set room configuration with agent dispatch and room metadata token.roomConfig = new RoomConfiguration({ agents: [ new RoomAgentDispatch({ agentName, metadata: JSON.stringify(options || {}), }), ], }); return token.toJwt(); }
t
You're close — add room metadata by creating/updating the room resource via the LiveKit server API/SDK, not inside
token.roomConfig
. The token's `roomConfig`/agent dispatch metadata goes to the agent's JobContext and won't populate
room.metadata
used in webhooks. Where to add it • Call your room-creation or room-update method on the server before the room is started (before first participant joins). Add the
agent_type
there so
room_started
and later
room_finished
include it. Example Node.js pattern (place this in server code that runs before issuing the token):
Copy code
// ensure room has metadata before agent/participant join
await liveKitService.createOrGetRoom(roomName, {
  metadata: {
    agent_type: agentName,
    ...otherMetadata,
  },
});

// then generate token with agent dispatch as you already do
const token = new AccessToken(...);
// add grants...
token.roomConfig = new RoomConfiguration({
  agents: [
    new RoomAgentDispatch({
      agentName,
      metadata: JSON.stringify(options || {}),
    }),
  ],
});
return token.toJwt();
If you must update metadata after room creation, update it while the room is still active (before first join for room_started; while participants remain for room_finished), and verify the update by fetching the room immediately after. If you want, I can provide: • a concrete
liveKitService.updateRoom
snippet for your SDK, or • a small flow to test timing so
room_started
includes the metadata. Which do you prefer?
a
yes please a concrete
liveKitService.updateRoom
snippet for your SDK
t
Below is a concise Node.js example showing how to update room metadata using the LiveKit server SDK (
RoomServiceClient
) and how to integrate it before generating the access token so `room_started`/`room_finished` can include
agent_type
. 1) Install SDK (if not already): • npm install livekit-server-sdk 2) Example snippet:
Copy code
const { RoomServiceClient } = require('livekit-server-sdk');
const { AccessToken, RoomConfiguration, RoomAgentDispatch } = require('livekit-server-sdk'); // adjust import if using ESM

const liveKitService = new RoomServiceClient(
  'https://your-livekit-url', // LiveKit API URL
  'YOUR_API_KEY',
  'YOUR_API_SECRET'
);

async function ensureRoomMetadataAndToken(roomName, participantName, participantIdentity, agentName, options = {}) {
  // 1) Ensure room exists and set persistent room metadata
  const metadataObj = {
    agent_type: agentName,
    ...options.metadata, // merge any additional metadata
  };
  // updateRoomMetadata expects a string
  await liveKitService.updateRoomMetadata(roomName, JSON.stringify(metadataObj));

  // Optionally verify the room immediately (optional)
  // const roomInfo = await liveKitService.getRoom(roomName);
  // console.log('room metadata after update:', roomInfo.metadata);

  // 2) Create token with agent dispatch (agent metadata goes to JobContext)
  const token = new AccessToken(
    'YOUR_API_KEY',
    'YOUR_API_SECRET',
    { identity: participantIdentity, name: participantName }
  );

  token.addGrant({
    room: roomName,
    roomJoin: true,
    canPublish: options.canPublish !== false,
    canSubscribe: options.canSubscribe !== false,
    canPublishData: options.canPublishData !== false,
  });

  token.roomConfig = new RoomConfiguration({
    agents: [
      new RoomAgentDispatch({
        agentName,
        metadata: JSON.stringify(options || {}),
      }),
    ],
  });

  return token.toJwt();
}
Timing notes: • Call
updateRoomMetadata
before the first participant joins so
room_started
includes the metadata. • To have
room_finished
include updated metadata, update while the room is still active (before the last participant leaves). • After calling
updateRoomMetadata
, you can
getRoom(roomName)
to verify the metadata persisted. Would you like a TypeScript/ESM version or a small test script to run locally? Sources: Managing participants | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Webhooks | LiveKit docs
a
so session means here , the duration between room_creation and room_finished or how it is?
t
Yes — in LiveKit a "session" typically means the room's active lifespan: from when the room starts (the first participant joins, triggering
room_started
) until it finishes (the last participant leaves, triggering
room_finished
). • `room_started`: emitted when the room is created / first participant joins. • `room_finished`: emitted when the last participant leaves and the room is closed. So session duration is effectively the time between those two events. (Note: sometimes "session" can refer to an individual participant connection in analytics, but the room-based session is the full shared lifespan.) Sources: Webhooks | LiveKit docs | Rooms, participants, and tracks | LiveKit docs | Analytics API | LiveKit docs
a
in livekit dashboard sessions data what are all the statuses maintaining for session can you give few sample records
t
You're asking what session statuses the LiveKit dashboard maintains and want sample records — here are the common inferred statuses and example session records you can expect from the Analytics API. Inferred session statuses • Active (Running) —
endedAt
/
endTime
is null and
numActiveParticipants > 0
. • Empty (Idle) — room exists,
numActiveParticipants = 0
, but
endedAt
is null (waiting for empty timeout). • Ended (Closed) —
endedAt
/
endTime
is set and
numActiveParticipants = 0
. • Egress states (separate field):
egress = 0
(never started),
1
(active),
2
(ended). Example session records (Analytics API style) {"sessionId":"RM_ABC123","roomName":"meeting-room-1","createdAt":"2025-09-29T135940Z","endedAt":null,"lastActive":"2025-09-29T141005Z","numParticipants":3,"numActiveParticipants":2,"egress":1} {"sessionId":"RM_DEF456","roomName":"meeting-room-2","createdAt":"2025-09-28T090000Z","endedAt":"2025-09-28T094500Z","lastActive":"2025-09-28T094455Z","numParticipants":4,"numActiveParticipants":0,"egress":2} {"sessionId":"RM_GHI789","roomName":"support-call-123","createdAt":"2025-09-30T101500Z","endedAt":null,"lastActive":"2025-09-30T102012Z","numParticipants":2,"numActiveParticipants":0,"egress":0} If you want, I can: • map these fields to the exact dashboard columns you see, or • fetch a sample response from your Analytics API (if you share a request you run) to confirm how your data appears. Which would you prefer? Sources: Analytics API | LiveKit docs | Agent insights in LiveKit Cloud | LiveKit docs
a
can you provide me the official document where this concept has been coverd
t
You can find the official LiveKit documentation covering session lifecycle, analytics, and dashboard/insights here: • Analytics API — session details (start/end, participants, timestamps): https://docs.livekit.io/home/cloud/analytics-api/#list-session-details • Agent session lifecycle and events (agent-specific session states): https://docs.livekit.io/agents/build/sessions/#lifecycle • Agent server lifecycle (server/job/session handling): https://docs.livekit.io/agents/server/#server-lifecycle • Agent insights / observability (how session data is surfaced in the dashboard): https://docs.livekit.io/agents/observability/ • Observability data hooks (exporting session artifacts and telemetry): https://docs.livekit.io/agents/observability/data If you want, I can point to the exact fields in the Analytics API responses that map to "Active / Empty / Ended" status or show snippet examples from those pages. Which would help most? Sources: Analytics API | LiveKit docs | Agent session | LiveKit docs | Agent server | LiveKit docs | Agent insights in LiveKit Cloud | LiveKit docs | Observability data hooks | LiveKit docs
a
how to run agent to get the logs in session tab session related data table in livekit cloud
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!