How to provide livekit sesstion with information a...
# ask-ai
g
How to provide livekit sesstion with information about the user from the database before the session is started. Lets say, have a separate API with "start_session" route that will create a room and provide the data from the DB to the room and the API return the link/creds to the room. Or suggest better implementation
t
Thanks for reaching out, Dima. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're on the right track—best practice is to fetch user data in your
start_session
endpoint and embed that data in the token you return, rather than pre-populating the room via a separate create-call. This keeps startup fast, avoids extra LiveKit API calls, and uses LiveKit features designed for this use case. Recommended flow 1. In your
start_session
endpoint: ◦ Query the user from your DB. ◦ Create an Access Token with the user's identity and room grants. ◦ Attach user info to the token using metadata (JSON blob) and/or attributes (key/value pairs). ◦ Return the room URL and signed token to the client. Why this is better • Rooms are auto-created when the first participant joins, so you don’t need a separate CreateRoom request. • Tokens carry the necessary context to configure the participant on join, avoiding race conditions and extra network calls. • Attributes are structured and updateable; metadata is good for carrying arbitrary JSON you want available immediately on join. Minimal Node.js example
Copy code
// inside /start_session
const user = await db.getUser(req.query.userId);
const token = new AccessToken(apiKey, apiSecret, {
  identity: user.id,
  name: user.name,
});
token.addGrant({
  roomJoin: true,
  room: 'my-room',
  canPublish: true,
  canSubscribe: true,
});
token.metadata = JSON.stringify({ profile: user.profile, prefs: user.prefs });
token.attributes = { 'user.role': user.role, 'user.plan': user.plan };

res.json({ token: await token.toJwt(), url: 'wss://your-livekit-url' });
Notes on usage after join • On the server or other participants, read
participant.metadata
and
attributes
to customize UI, routing, or access. • If you need to change structured data later, update attributes via the participant update API. If you'd like, I can: • Provide a full code sample for your language (Node/Python/Go). • Suggest which fields are better as attributes vs metadata for your particular user model. Which language are you using and which user fields do you want to include? Sources: Participant attributes and metadata | LiveKit docs | Authentication | LiveKit docs | Generating tokens | LiveKit docs | CreateRoom() is Taking Too Long | Job lifecycle | LiveKit docs