how do I pass metadata when creating a jwt token i...
# ask-ai
w
how do I pass metadata when creating a jwt token in node?
t
Thanks for reaching out, Nathan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! When you’re creating a JWT token in Node.js for LiveKit and want to pass along some metadata, there are a couple of friendly ways to do it. Let me walk you through them: Method 1: Pass metadata in constructor options
Copy code
import { AccessToken } from 'livekit-server-sdk';

const at = new AccessToken('api-key', 'secret-key', {
  identity: 'user-identity',
  metadata: 'custom metadata string', // Pass metadata here
});

at.addGrant({
  room: 'room-name',
  roomJoin: true,
});

const token = await at.toJwt();
console.log('access token', token);
Method 2: Set metadata using the setter
Copy code
import { AccessToken } from 'livekit-server-sdk';

const at = new AccessToken('api-key', 'secret-key', {
  identity: 'user-identity',
});

at.metadata = 'custom metadata string'; // Set metadata using setter

at.addGrant({
  room: 'room-name',
  roomJoin: true,
});

const token = await at.toJwt();
Just a few helpful notes: • The
metadata
field expects a string. If you want to share more complex data, you can always serialize it as JSON. • This metadata is accessible to other participants through the
Participant.metadata
property in client SDKs—pretty handy! • If you’d like to update metadata after the connection is established, just make sure to enable
canUpdateOwnMetadata
in the video grant. If you have any questions or need a hand with anything else, please don’t hesitate to ask. I’m here to help! Sources: Docs::Home | examples/agent-dispatch/index.ts | web/src/app/api/token/route.ts | web/app/api/connection-details/route.ts
w
cool, now how do I access it on my livekit server when connecting?
t
I'm glad you're looking to access metadata on your LiveKit server when a participant connects! You can easily retrieve it from the participant's metadata field. Let me walk you through it: 1. Access Metadata in Client SDKs Once a participant joins, their metadata is available via the
Participant.metadata
property. Here's a simple example:
Copy code
// JavaScript\nroom.on(RoomEvent.ParticipantMetadataChanged, (oldMetadata, participant) => {\n  console.log('Metadata changed from', oldMetadata, 'to', participant.metadata);\n});
2. Update Metadata from Server APIs You can also update or retrieve a participant's metadata using the server API. For instance, in Node.js:
Copy code
roomServiceClient.updateParticipant('room', 'identity', {\n  metadata: 'updated metadata',\n});
3. Metadata Characteristics • The
metadata
field is a single string. If you want to store structured data, you can serialize it as JSON. • Keep in mind, metadata is limited to 64 KiB and is synchronized with all participants. • For real-time updates, just listen for metadata change events in your client application. If you have any questions or want me to provide more examples, please feel free to ask. I'm here to help! Sources: Docs::Home
w
is there a way I can get access to it before connecting?
t
Thanks for reaching out! Could you please share a bit more about how you’re planning to use the metadata before connecting? For instance, are you looking to validate or process it on the server side before letting the participant join? Understanding this will help me give you the best possible guidance.
w
I'm looking to start the session with a specific agent depending on a piece of metadata
t
Hi there! To help you route participants to specific agents based on metadata before they connect, you can include that metadata right in the participant's access token and then use it to dispatch agents accordingly. Let me walk you through it step-by-step: 1. Include Metadata in the Access Token When you're creating the participant's access token, just add the metadata that holds the routing info (like user ID, language, or department). Here's an example:
Copy code
const at = new AccessToken('api-key', 'secret-key', {\n  identity: 'user-identity',\n  metadata: JSON.stringify({ user_id: '12345', language: 'es', department: 'support' }),\n});
2. Dispatch Agents Based on Metadata Next, you can set up the room to dispatch specific agents using that metadata. Here's a simple example in Python:
Copy code
token = (\n    AccessToken()\n    .with_identity("my_participant")\n    .with_grants(VideoGrants(room_join=True, room=room_name))\n    .with_room_config(RoomConfiguration(\n        agents=[\n            RoomAgentDispatch(\n                agent_name="sales-agent",\n                metadata='{"user_id": "12345", "language": "es", "department": "support"}'\n            ),\n        ],\n    ))\n    .to_jwt()\n)
3. Use Metadata in the Agent's Entrypoint On the server side, your agent can access this metadata to decide how to route the participant. Here's how that might look:
Copy code
async def entrypoint(ctx: JobContext):\n    metadata = json.loads(ctx.job.metadata)\n    user_language = metadata.get("language")\n    department = metadata.get("department")\n\n    if department == "support":\n        agent = SupportAgent(language=user_language)\n    elif department == "sales":\n        agent = SalesAgent()
Just a couple of quick notes to keep in mind: • Since metadata is passed as a string, using JSON helps keep your data structured nicely. • If you specify an
agent_name
, automatic dispatching will be turned off. • The room will be created automatically if it doesn't already exist when dispatching. I hope this helps clarify things! If you have any questions or want to dive deeper into any part, just let me know—I'm here to help! Sources: Agent dispatch | LiveKit Docs | examples/agent_dispatch.py | Job lifecycle | LiveKit Docs | External data and RAG | LiveKit Docs | Participant attributes and metadata | LiveKit Docs