TanStack Start and Router
Mint tokens in server functions, prepare rooms in loaders, and keep one connection across navigation.
The pattern: server functions hold your service key and mint short-lived tokens; route loaders prepare data on the server for the first request and over RPC on client navigation; a pathless layout route owns the Lynkoria client, so moving between pages inside it keeps one connection and leaving it disconnects.
A complete, tested app lives in apps/example-tanstack-start in the Lynkoria repository. Its Playwright suite checks the server-rendered room from the loader, hydration without errors, a single connection, that navigating between rooms reuses that connection and leaving the layout closes it, realtime chat between two users, and that client assets contain no server SDK code, secrets or zod. The app is styled with Tailwind on the Lynkoria brand tokens and includes route pending and error states. Run it locally with pnpm dev:example from the repository root (it serves http://localhost:3200; pnpm dev must be running for the API).
Install
pnpm add @lynkoria/server @lynkoria/client @lynkoria/reactServer environment: LYNKORIA_API_URL, LYNKORIA_SERVICE_KEY (never expose it through VITE_ variables).
Server functions
// src/server/lynkoria.ts
import { createServerFn, createServerOnlyFn } from '@tanstack/react-start';
import { createLynkoriaServer, type LynkoriaServer } from '@lynkoria/server';
import { getSession } from './auth'; // your authentication
let instance: LynkoriaServer | undefined;
// Throws if called in the browser; Start also strips server function bodies from client bundles.
const lynkoria = createServerOnlyFn(
(): LynkoriaServer =>
(instance ??= createLynkoriaServer({
baseUrl: process.env.LYNKORIA_API_URL!,
serviceKey: process.env.LYNKORIA_SERVICE_KEY!,
})),
);
export const getMessagingToken = createServerFn({ method: 'POST' }).handler(async () => {
const session = await getSession();
return lynkoria().sessions.messagingToken({ userId: session.userId, deviceId: session.deviceId });
});
export const ensureRoom = createServerFn()
.validator((input: { room: string }) => input)
.handler(async ({ data }) => {
const session = await getSession();
const conversation = await lynkoria().conversations.create({
type: 'group',
productConversationId: `room-${data.room}`, // idempotent
memberIds: [session.userId],
});
return { conversationId: conversation.id };
});Layout route owns the client
// src/routes/_app.tsx
import { createLynkoria } from '@lynkoria/client';
import { LynkoriaProvider } from '@lynkoria/react';
import { createFileRoute, Outlet } from '@tanstack/react-router';
import { useServerFn } from '@tanstack/react-start';
import { useState } from 'react';
import { getMessagingToken } from '../server/lynkoria';
export const Route = createFileRoute('/_app')({ component: AppLayout });
function AppLayout() {
const mintToken = useServerFn(getMessagingToken);
// No I/O until LynkoriaProvider connects in the browser, so this is safe during SSR.
const [client] = useState(() =>
createLynkoria({
baseUrl: import.meta.env.VITE_LYNKORIA_API_URL,
getMessagingToken: () => mintToken(),
}),
);
return (
<LynkoriaProvider client={client}>
<Outlet />
</LynkoriaProvider>
);
}Pages under _app/ share the connection. A route outside the layout (for example /about) unmounts the provider and disconnects. Do not create the client inside a page route: every navigation would reconnect.
Loaders prepare data; components subscribe
// src/routes/_app/rooms.$room.tsx
import { useConversation } from '@lynkoria/react';
import { createFileRoute } from '@tanstack/react-router';
import { ensureRoom } from '../../server/lynkoria';
export const Route = createFileRoute('/_app/rooms/$room')({
loader: ({ params }) => ensureRoom({ data: { room: params.room } }),
component: RoomPage,
});
function RoomPage() {
const { conversationId } = Route.useLoaderData();
// Keyed by conversation: switching rooms resets the list and stops tracking the previous room.
const { messages, send } = useConversation(conversationId);
// …render messages and a form that calls send(text)
}TanStack Router without Start
The same layout-route pattern applies to a client-only TanStack Router app. Mint tokens from your own backend endpoint instead of a server function:
import { createLynkoria } from '@lynkoria/client';
export const client = createLynkoria({
baseUrl: import.meta.env.VITE_LYNKORIA_API_URL,
getMessagingToken: async () =>
(await fetch('/api/lynkoria/messaging-token', { method: 'POST' })).json(),
});Use route beforeLoad for protected areas (redirect to sign-in when there is no session) so the realtime layout mounts only for signed-in users.
Calls
useCall().join({ getJoinToken }) loads livekit-client on the first join (a separate chunk of about 143 KB gzip). Mint the join token in a server function the same way as the messaging token. The browser call flow is covered end to end in the Next.js example; the client code is identical.
Allowed origins
Add your site's origin to the project environment's allowed origins (and ALLOWED_ORIGINS when self-hosting). Browsers connect to the API directly.