Next.js
Use Lynkoria in the Next.js App Router with server-side token minting and client-side realtime.
The pattern: your service key stays in server code (a server-only module used by Route Handlers and Server Components); the browser gets short-lived tokens from your Route Handlers and connects to Lynkoria directly from a Client Component. Media and sockets never run during server rendering.
A complete, tested app lives in apps/example-nextjs in the Lynkoria repository. Its Playwright suite checks server rendering, hydration without errors, a single realtime connection, chat between two users, a call through LiveKit with fake media (including a published camera rendered for the other participant), and that client bundles contain no server SDK code, secrets or zod. The app is styled with Tailwind on the Lynkoria brand tokens and shows chat, typing, call controls and connection states. Run it locally with pnpm dev:example from the repository root (it serves http://localhost:3100; pnpm dev must be running for the API).
Install
pnpm add @lynkoria/server @lynkoria/client @lynkoria/react server-onlyEnvironment (server only; never prefix the key with NEXT_PUBLIC_):
LYNKORIA_API_URL=https://api.lynkoria.com
LYNKORIA_SERVICE_KEY=lynk_live_…Server: one server-only module
// lib/lynkoria.server.ts
import 'server-only';
import { createLynkoriaServer, type LynkoriaServer } from '@lynkoria/server';
let instance: LynkoriaServer | undefined;
export function lynkoria(): LynkoriaServer {
// Created on first use so `next build` does not need the secret.
return (instance ??= createLynkoriaServer({
baseUrl: process.env.LYNKORIA_API_URL!,
serviceKey: process.env.LYNKORIA_SERVICE_KEY!,
}));
}server-only makes the build fail if a Client Component imports this file.
Route Handlers mint tokens
Authenticate the user with your own session first; Lynkoria trusts what your backend asserts.
// app/api/lynkoria/messaging-token/route.ts
import { lynkoria } from '@/lib/lynkoria.server';
import { getSession } from '@/lib/auth'; // your authentication
export async function POST(): Promise<Response> {
const session = await getSession();
if (!session) return Response.json({ error: 'unauthenticated' }, { status: 401 });
const token = await lynkoria().sessions.messagingToken({
userId: session.userId,
deviceId: session.deviceId,
});
return Response.json(token, { headers: { 'cache-control': 'no-store' } });
}// app/api/lynkoria/calls/[callKey]/join/route.ts
import { getSession } from '@/lib/auth';
import { lynkoria } from '@/lib/lynkoria.server';
export async function POST(_: Request, { params }: { params: Promise<{ callKey: string }> }) {
const session = await getSession();
if (!session) return Response.json({ error: 'unauthenticated' }, { status: 401 });
const { callKey } = await params;
// Decide here whether this user may join this call.
const call = await lynkoria().calls.create({ productCallId: callKey, type: 'group' }); // idempotent
const { url, token } = await lynkoria().calls.joinToken({
callId: call.id,
userId: session.userId,
deviceId: session.deviceId,
displayName: session.name,
});
return Response.json({ url, token }, { headers: { 'cache-control': 'no-store' } });
}Server Components can call the server SDK directly
// app/rooms/[room]/page.tsx (Server Component)
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { lynkoria } from '@/lib/lynkoria.server';
import { RoomClient } from './room-client';
export default async function Page({ params }: { params: Promise<{ room: string }> }) {
const { room } = await params;
const session = await getSession();
if (!session) redirect('/sign-in');
const conversation = await lynkoria().conversations.create({
type: 'group',
productConversationId: `room-${room}`, // idempotent
memberIds: [session.userId],
});
return <RoomClient apiUrl={process.env.LYNKORIA_API_URL!} conversationId={conversation.id} />;
}Pass only non-secret values (the API origin, ids) to Client Components.
Client Component connects and renders
// app/rooms/[room]/room-client.tsx
'use client';
import { createLynkoria } from '@lynkoria/client';
import { LynkoriaProvider, useConnectionState, useConversation } from '@lynkoria/react';
import { useState } from 'react';
export function RoomClient({ apiUrl, conversationId }: { apiUrl: string; conversationId: string }) {
// One client per mount; it connects in an effect, so nothing runs during server rendering.
const [client] = useState(() =>
createLynkoria({
baseUrl: apiUrl,
getMessagingToken: async () =>
(await fetch('/api/lynkoria/messaging-token', { method: 'POST' })).json(),
}),
);
return (
<LynkoriaProvider client={client}>
<Messages conversationId={conversationId} />
</LynkoriaProvider>
);
}
function Messages({ conversationId }: { conversationId: string }) {
const state = useConnectionState(); // 'idle' during server rendering
const { messages, send } = useConversation(conversationId);
return (
<section aria-busy={state !== 'connected'}>
<ul>
{messages.map((m) => (
<li key={m.id}>{m.deletedAt ? 'Message deleted' : m.body}</li>
))}
</ul>
<button onClick={() => void send('Hello')}>Say hello</button>
</section>
);
}@lynkoria/reactis marked"use client"; import it only from Client Components.LynkoriaProviderkeeps one connection under Strict Mode in development.- Calls:
useCall().join({ getJoinToken })loadslivekit-clienton the first join, so pages that only chat never download the media engine (about 143 KB gzip). Render video with@livekit/components-reactby passingsession.roomto itsRoomContext.
Allowed origins
Add your site's origin (for example https://app.example.com) to the project environment's allowed origins in the console, and the API's ALLOWED_ORIGINS for self-hosted deployments. Browsers connect to the API directly.
Bundle sizes
Measured on 2026-11-13 (esbuild, minified, React and livekit-client external): @lynkoria/client messaging 51.6 KB / 16.8 KB gzip; with @lynkoria/react 55.3 KB / 18.1 KB gzip. livekit-client is a separate chunk of about 143 KB gzip, loaded on the first call join.