In my backend i generate the Session Token like th...
# ask-ai
f
In my backend i generate the Session Token like this:
Copy code
/**
   * Generate a LiveKit access token for a user to join an agent call
   */
  async generateUserToken(
    agentCode: string,
    userName?: string,
  ): Promise<GenerateUserTokenResult> {
    // Create unique room name: {agentCode}-{timestamp}-{randomId}
    const timestamp = Date.now();
    const randomId = nanoid(8);
    const roomName = `${agentCode}-${timestamp}-${randomId}`;

    // Generate user identity
    const userIdentity = userName || `user-${nanoid(8)}`;

    const agentName = `nebula-${this.agentEnv}`;

    this.logger.log(
      { agentCode, roomName, userIdentity, agentEnv: this.agentEnv },
      'Generating LiveKit token',
    );

    // Create access token
    // NOTE: We do NOT pass the userName to avoid leaking it to the agent context
    // The agent should learn the user's name through conversation, not from metadata
    const token = new AccessToken(this.apiKey, this.apiSecret, {
      identity: userIdentity,
      // name: userName,  // Commented out to prevent name leak
    });

    // Add video grants for room join
    token.addGrant({
      room: roomName,
      roomJoin: true,
      canPublish: true,
      canSubscribe: true,
    });

    // Set participant metadata
    token.metadata = JSON.stringify({
      agentCode,
    });

    token.attributes = {
      agentCode,
    };

    // Configure room to dispatch the agent when participant joins
    token.roomConfig = new RoomConfiguration({
      agents: [
        new RoomAgentDispatch({
          agentName: agentName,
          metadata: JSON.stringify({ agentCode }),
        }),
      ],
    });

    const jwt = await token.toJwt();

    this.logger.log(
      { roomName, agentName },
      'LiveKit token generated successfully with agent dispatch',
    );

    return {
      token: jwt,
      serverUrl: this.livekitUrl,
      roomName,
    };
  }
Is there a way to make the agent join the room in advance when we generate the token instead of when the user joins to the room ? So it starts joining while the user is also joining
t
Thanks for reaching out, Carlos. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It sounds like you want the agent to start connecting before (or as) the user joins, rather than waiting until after. You’re already on the right path with
roomConfig
and
RoomAgentDispatch
in the token. That configuration dispatches the agent when the room is created. To have the agent join concurrently with the user, create/initialize the room and dispatch the agent at token generation time (i.e., before the client calls join) using explicit agent dispatch. This lets the agent spin up while the user is connecting. If you prefer a deferred approach, you can also trigger the agent on a participant-joined event via a server webhook. For details, see: • Token room configuration and agent dispatch docs • Frontend timing/dispatch guidance here Sources: Authentication | LiveKit Docs | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | Voice Assistant Applications | livekit/livekit_composite | DeepWiki | Web and mobile frontends | LiveKit Docs | Live Conversations with AI using ChatGPT and WebRTC
f
So in the backend i dispatch the agent join as soon as i create the token ?
t
You’re asking if you should dispatch the agent when generating the token. Yes—embed the agent in the token’s
roomConfig
(as you’re doing). Then, when the room is created, the agent is dispatched immediately, so it can start joining while the user connects. You don’t need a separate backend call; just return the token and let the client join. If you want the agent to start even earlier, you can proactively create the room server-side before the client joins, using the same
roomConfig
, so dispatch starts right away. Sources: Agent dispatch | LiveKit Docs | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | Voice Assistant Applications | livekit/livekit_composite | DeepWiki | Web and mobile frontends | LiveKit Docs
f
How would i do it ? Can you give me a JavaScript Snippet ?
t
You’re asking for a JavaScript snippet to dispatch the agent at token generation time. Here’s a minimal Node/Express example that embeds
roomConfig
with
RoomAgentDispatch
so the agent starts as the room is created when the client joins.
Copy code
import express from 'express';
import { AccessToken } from 'livekit-server-sdk';
import { RoomConfiguration, RoomAgentDispatch } from '@livekit/protocol';

const app = express();
app.use(express.json());

app.post('/connection-details', async (req, res) => {
  const roomName = req.body.roomName || `room-${Math.random().toString(36).slice(2, 8)}`;
  const identity = req.body.identity || `user-${Math.random().toString(36).slice(2, 8)}`;
  const agentName = req.body.agentName || 'my-agent';

  const token = new AccessToken(process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET, {
    identity,
  });

  token.addGrant({
    room: roomName,
    roomJoin: true,
    canPublish: true,
    canSubscribe: true,
  });

  token.roomConfig = new RoomConfiguration({
    agents: [
      new RoomAgentDispatch({
        agentName,
        metadata: JSON.stringify({ source: 'token-gen' }),
      }),
    ],
  });

  const jwt = await token.toJwt();
  res.json({
    serverUrl: process.env.LIVEKIT_URL,
    roomName,
    token: jwt,
  });
});

app.listen(3000);
Would you like the same pattern adapted for Next.js API routes or multiple agents in one room? Sources: Agent dispatch | LiveKit Docs | Authentication | LiveKit Docs | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | Generating tokens | LiveKit docs | Voice Assistant Applications | livekit/livekit_composite | DeepWiki
f
But that will create the Room in advance and make the agent join before the User starts joining ?
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!
f
What i need is to 1. Generate the access token for the user so it can join 2. While the user join, trigger the agent joining (So instead of the agent joining after the user, it starts joining while the user also joins) Is that possible ?