1. Install LiveKit SDK
Install the LiveKit SDKs for the server and client:
yarn add livekit-server-sdk livekit-client @livekit/components-react
npm install livekit-server-sdk livekit-client @livekit/components-react --save
2. Keys and Configuration
To start, your app needs an LiveKit API key and secret, as well as your LiveKit project URL.
Create a new file at .env.development.local
with the following contents. Do not commit this file!
LIVEKIT_API_KEY=<API Key>LIVEKIT_API_SECRET=<API Secret hidden>LIVEKIT_URL=%{wsURL}%
3. Create token endpoint
Create a new file at /api/get_lk_token.ts
with the following contents:
import { AccessToken } from "livekit-server-sdk";import { NextApiRequest, NextApiResponse } from "next";export default async function handler(req: NextApiRequest, res: NextApiResponse) {const room = req.query.room as string;const username = req.query.username as string;if (req.method !== "GET") {return res.status(400).json({ error: "Invalid method" });} else if (!room) {return res.status(400).json({ error: 'Missing "room" query parameter' });} else if (!username) {return res.status(400).json({ error: 'Missing "username" query parameter' });}const apiKey = process.env.LIVEKIT_API_KEY;const apiSecret = process.env.LIVEKIT_API_SECRET;const wsUrl = process.env.LIVEKIT_WS_URL;if (!apiKey || !apiSecret || !wsUrl) {return res.status(500).json({ error: "Server misconfigured" });}const at = new AccessToken(apiKey, apiSecret, { identity: username });at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });res.status(200).json({ token: at.toJwt() });}
4. Make a page in your web app
Make a new file at /pages/room.tsx
with the following contents:
import { LiveKitRoom, VideoConference } from "@livekit/components-react";import { useEffect, useState } from "react";export default () => {const room = "quickstart-room";const name = "quickstart-user"; // TODO: interpolate with user nameconst [token, setToken] = useState("");useEffect(() => {(async () => {const resp = await fetch(`/api/get_lk_token?room=${room}&username=${name}`);const data = await resp.json();setToken(data.token);})();});if (token === "") {return <div>Getting token...</div>;}return (<LiveKitRoomserverUrl={process.env.NEXT_PUBLIC_LIVEKIT_URL}token={token}connect={true}video={true}audio={true}><VideoConference /></LiveKitRoom>);};
5. Load the page and connect
Start your server with:
yarn dev
npm dev
And then go to localhost:8000/room
in your browser.