{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"nextjs-api-token-route","title":"NextJS API route to get a LiveKit session token","description":"A NextJS API route to generate a LiveKit session token while keeping your API keys private.","dependencies":["livekit-server-sdk","@livekit/protocol"],"files":[{"path":"components/agents-ui/nextjs-api-token-route.ts","content":"import { NextResponse } from 'next/server';\nimport { AccessToken, type AccessTokenOptions, type VideoGrant } from 'livekit-server-sdk';\nimport { RoomConfiguration } from '@livekit/protocol';\n\ntype ConnectionDetails = {\n  serverUrl: string;\n  roomName: string;\n  participantName: string;\n  participantToken: string;\n};\n\n// NOTE: you are expected to define the following environment variables in `.env.local`:\nconst API_KEY = process.env.LIVEKIT_API_KEY;\nconst API_SECRET = process.env.LIVEKIT_API_SECRET;\nconst LIVEKIT_URL = process.env.LIVEKIT_URL;\n\n// don't cache the results\nexport const revalidate = 0;\n\nexport async function POST(req: Request) {\n  if (process.env.NODE_ENV !== 'development') {\n    throw new Error(\n      'THIS API ROUTE IS INSECURE. DO NOT USE THIS ROUTE IN PRODUCTION WITHOUT AN AUTHENTICATION LAYER.',\n    );\n  }\n\n  try {\n    if (LIVEKIT_URL === undefined) {\n      throw new Error('LIVEKIT_URL is not defined');\n    }\n    if (API_KEY === undefined) {\n      throw new Error('LIVEKIT_API_KEY is not defined');\n    }\n    if (API_SECRET === undefined) {\n      throw new Error('LIVEKIT_API_SECRET is not defined');\n    }\n\n    // Parse room config from request body.\n    const body = await req.json();\n    // Recreate the RoomConfiguration object from JSON object.\n    const roomConfig = body?.room_config\n      ? RoomConfiguration.fromJson(body.room_config, { ignoreUnknownFields: true })\n      : new RoomConfiguration();\n\n    // Generate participant token\n    const participantName = 'user';\n    const participantIdentity = `voice_assistant_user_${Math.floor(Math.random() * 10_000)}`;\n    const roomName = `voice_assistant_room_${Math.floor(Math.random() * 10_000)}`;\n\n    const participantToken = await createParticipantToken(\n      { identity: participantIdentity, name: participantName },\n      roomName,\n      roomConfig,\n    );\n\n    // Return connection details\n    const data: ConnectionDetails = {\n      serverUrl: LIVEKIT_URL,\n      roomName,\n      participantName,\n      participantToken,\n    };\n    const headers = new Headers({\n      'Cache-Control': 'no-store',\n    });\n    return NextResponse.json(data, { headers });\n  } catch (error) {\n    if (error instanceof Error) {\n      console.error(error);\n      return new NextResponse(error.message, { status: 500 });\n    }\n  }\n}\n\nfunction createParticipantToken(\n  userInfo: AccessTokenOptions,\n  roomName: string,\n  roomConfig: RoomConfiguration,\n): Promise<string> {\n  const at = new AccessToken(API_KEY, API_SECRET, {\n    ...userInfo,\n    ttl: '15m',\n  });\n  const grant: VideoGrant = {\n    room: roomName,\n    roomJoin: true,\n    canPublish: true,\n    canPublishData: true,\n    canSubscribe: true,\n  };\n  at.addGrant(grant);\n\n  if (roomConfig) {\n    at.roomConfig = roomConfig;\n  }\n\n  return at.toJwt();\n}\n","type":"registry:component","target":"app/api/token/route.ts"}],"categories":["agents","api"],"type":"registry:page"}