give me a js function that takes agent_name and ro...
# ask-ai
b
give me a js function that takes agent_name and room_name as input and al livekit creds from .env and generates token and room_name
t
Thanks for reaching out, Aman. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Below is a concise Node.js function that reads LiveKit creds from a .env file (using dotenv), takes
agent_name
and
room_name
, and returns a generated JWT token plus the room name. It uses the
livekit-server-sdk
. 1) Install: • npm install livekit-server-sdk dotenv 2) .env: • LIVEKIT_API_KEY=your_api_key • LIVEKIT_API_SECRET=your_api_secret 3) Code:
Copy code
require('dotenv').config();

const { AccessToken, VideoGrant } = require('livekit-server-sdk');

/**
 * Generates a LiveKit access token for a given agent and room.
 * @param {string} agent_name
 * @param {string} room_name
 * @returns {{ token: string, room_name: string }}
 */
function generateLiveKitToken(agent_name, room_name) {
  const apiKey = process.env.LIVEKIT_API_KEY;
  const apiSecret = process.env.LIVEKIT_API_SECRET;

  if (!apiKey || !apiSecret) {
    throw new Error('LIVEKIT_API_KEY and LIVEKIT_API_SECRET must be set in .env');
  }

  const at = new AccessToken(apiKey, apiSecret, {
    identity: agent_name,
    name: agent_name,
  });

  const grant = new VideoGrant({
    roomJoin: true,
    room: room_name,
    // canPublish, canSubscribe, canPublishData are allowed by default when roomJoin is true.
  });

  at.addGrant(grant);

  const token = at.toJwt();
  return { token, room_name };
}

module.exports = { generateLiveKitToken };
Need this function to also create the room server-side (if it doesn't exist) or set specific publish/subscribe flags? Sources: server-sdk-js | livekit/livekit_composite | DeepWiki