Integration
How to Display an AI Avatar in Next.js: Adding avacast to the App Router
A step-by-step walkthrough of the App Router setup, from creating a session on the server to passing it to the SDK in the browser.
What you need
- An API key: issue one under "API keys" in the dashboard.
- An avatar ID:
GET /v1/avatarsreturns the list. - The SDK:
npm install avacast
List avatars
curl https://api.avacast.jp/v1/avatars \
-H "Authorization: Bearer $AVACAST_API_KEY"Put the API key in .env.local and do not prefix it with NEXT_PUBLIC_. With the prefix, the key is sent to the browser.
.env.local
AVACAST_API_KEY=sk_live_...
AVACAST_AVATAR_ID=avt_xxxxxxxxA Route Handler that creates the session
Call POST /v1/sessions on the server and return only the values the browser needs. The browser receives client_token and webrtc; the API key is not returned.
app/api/avacast/session/route.ts
export async function POST() {
// In production, add authentication so that only signed-in users can call this
const res = await fetch('https://api.avacast.jp/v1/sessions', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.AVACAST_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ avatar_id: process.env.AVACAST_AVATAR_ID }),
});
const body = await res.json();
if (!res.ok) {
return Response.json({ error: body.error.code }, { status: res.status });
}
const { session_id, client_token, webrtc } = body;
return Response.json({ session_id, client_token, webrtc });
}Billing is based on the time the session is open. Add a Route Handler for ending the session as well, so that it can be closed when you are done. In Next.js 16, params is a Promise, so await it.
app/api/avacast/session/[id]/route.ts
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
await fetch(`https://api.avacast.jp/v1/sessions/${id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${process.env.AVACAST_API_KEY}` },
});
return new Response(null, { status: 204 });
}If the end call is never made, the session still closes automatically at the plan's maximum length or when no speech continues for a set time (180 seconds by default).
A client component that shows the video
The SDK uses the browser's WebRTC, so run it inside useEffect in a 'use client' component. attach can be called before or after start.
app/components/avatar.tsx
'use client';
import { AvacastSession } from 'avacast';
import { useEffect, useRef, useState } from 'react';
export function Avatar() {
const videoRef = useRef<HTMLVideoElement>(null);
const [session, setSession] = useState<AvacastSession | null>(null);
useEffect(() => {
let s: AvacastSession | null = null;
let sessionId: string | null = null;
let cancelled = false;
(async () => {
const res = await fetch('/api/avacast/session', { method: 'POST' });
const { session_id, client_token, webrtc } = await res.json();
if (cancelled) {
// The user left before creation finished (the first StrictMode run also lands here)
void fetch(`/api/avacast/session/${session_id}`, { method: 'DELETE' });
return;
}
sessionId = session_id;
s = new AvacastSession(client_token, {
signalingUrl: webrtc.signaling_url,
iceServers: webrtc.ice_servers,
eventsUrl: webrtc.events_url,
});
if (videoRef.current) s.attach(videoRef.current);
s.on('session.ready', () => setSession(s));
await s.start();
})();
return () => {
cancelled = true;
void s?.stop();
// Close the session when the user leaves (keepalive sends it during page navigation too)
if (sessionId) {
void fetch(`/api/avacast/session/${sessionId}`, { method: 'DELETE', keepalive: true });
}
};
}, []);
return (
<div>
<video ref={videoRef} autoPlay playsInline />
<button
type="button"
disabled={!session}
onClick={() => session?.speak('Thank you for getting in touch.')}
>
Speak
</button>
</div>
);
}- Call
speakafter the video has arrived (aftersession.ready). Calling it earlier returnssession_not_connected. - During development, React StrictMode runs
useEffecttwice. The session from the first run is closed in the cleanup, so it does not stay open. - The SDK's
speakauthenticates withclient_token, so calling it from the browser does not expose the API key.
Adding it to a page
app/page.tsx
import { Avatar } from './components/avatar';
export default function Page() {
return <Avatar />;
}With this in place, opening the page shows the avatar video, and the button starts speech. If you compose the text on the server, call POST /v1/sessions/:id/speak from the server instead of speak in the browser. See the API reference (in Japanese) for details.
FAQ
Can I use the API key in the browser?
No. Keep the API key in server environment variables only, and pass the browser client_token and webrtc, which work for a single session only.
Does the same approach work with the Pages Router?
Yes. The split is the same: put the session creation in an API route (pages/api) and run the SDK in a browser-side component.
What happens if I forget to close a session?
It closes automatically when no speech continues (180 seconds by default) or when it reaches the plan's maximum length. Billing is based on the time the session is open, so it is worth implementing a close when the user leaves the page.
30 minutes a month free
Try it free