Connecting a Next.js frontend
Up to now you have been talking to the agent through the LiveKit playground. Great for testing, not great for customers. Now we put a real interface in front of the agent. LiveKit ships React hooks that make this almost embarrassingly easy.
How the frontend joins the conversation
The browser asks the backend for a token, connects to LiveKit, and the agent joins the same room.
'use client';
import { LiveKitRoom, RoomAudioRenderer, StartAudio } from '@livekit/components-react';
import { useState } from 'react';
export default function VoicePage() {
const [token, setToken] = useState<string | null>(null);
const [url, setUrl] = useState<string | null>(null);
async function connect() {
const res = await fetch('/api/connection', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ participant_name: 'Guest' }),
});
const data = await res.json();
setToken(data.participant_token);
setUrl(data.server_url);
}
if (!token || !url) {
return <button onClick={connect}>Start ordering</button>;
}
return (
<LiveKitRoom token={token} serverUrl={url} connect audio video={false}>
<RoomAudioRenderer />
<StartAudio label="Click to enable audio" />
</LiveKitRoom>
);
}LiveKitRoom handles the connection, RoomAudioRenderer pipes agent audio to the speakers, and StartAudio covers the browser autoplay policy. Most browsers will not play audio until the user interacts with the page.
Browsers block audio from playing until the user clicks something. It stops random websites from blaring noise at you. StartAudio is the official way to satisfy that gesture requirement. Without it, the agent will happily send audio that the browser silently refuses to play.
Quiz: Quiz
Loading practice…