Connect server data to your browser scene
Read a system with its credential on your server, send the reading to the browser, and show it on an object of the scene. The starter's /connected page, end to end.
Run credentialed connections on your server. Your application sends the readings to the browser, where Klorad updates the corresponding objects.
The packages do not include a transport from a server to browsers, so this guide shows the
shortest one: an endpoint of your application that the browser polls. It continues the
quickstart with the same hall and the same entrance counter, and its
code is the /connected page of the quickstart starter.
Who does what
| Step | Who | Where |
|---|---|---|
| Hold the credential, call the system, validate its answer | Your application | lib/counter.ts, on the server |
| Send the browser only the reading it needs | Your application | app/api/occupancy/route.ts |
| Read that endpoint on an interval | Klorad: pollingSource | app/connected/connected-twin.tsx, in the browser |
| Put the reading on the bound object, keep the newest, mark it stale | Klorad: the scene | the same file, through KloradProvider and Connector |
| Show the value and the failure | Your application, with useLatest | the same file |
1. Keep the credential on the server
The counter's address and token come from the server's environment. The answer is validated before it becomes a reading; anything else is refused.
import { z } from "zod";
// Server code only: this module reads the credential. Import it from route handlers, never from a "use client" file.
/** What the counter's API promises to send. Anything else is refused before it reaches a scene. */
const CounterResponse = z.object({
device: z.string(),
people: z.number().int().nonnegative(),
measuredAt: z.string().datetime(),
});
/** The one reading the browser needs, and nothing else from the upstream answer. */
export type Occupancy = { entity: string; value: number; unit: "people"; observedAt: number };
/** Reads the counter with the credential kept in the server's environment, and validates what comes back. */
export async function readCounter(): Promise<Occupancy> {
const url = process.env.COUNTER_URL;
const token = process.env.COUNTER_TOKEN;
if (!url || !token) throw new Error("COUNTER_URL and COUNTER_TOKEN are not set: copy .env.example to .env.local");
const response = await fetch(url, { headers: { authorization: `Bearer ${token}` }, cache: "no-store" });
if (!response.ok) throw new Error(`the counter answered ${response.status}`);
const body = CounterResponse.parse(await response.json());
return { entity: body.device, value: body.people, unit: "people", observedAt: Date.parse(body.measuredAt) };
}2. Send the browser only the reading
The route reads the counter once per request and returns four fields. A failure becomes a 502 with a message that names neither the address nor the credential.
import { NextResponse } from "next/server";
import { readCounter } from "../../../lib/counter";
// Each request reads the counter once and returns. Nothing keeps running on the server between requests,
// so the route works the same on a long running server and on a serverless platform.
export const dynamic = "force-dynamic";
export async function GET() {
try {
return NextResponse.json(await readCounter(), { headers: { "cache-control": "no-store" } });
} catch (error) {
// The browser learns that the reading failed, never the credential or the upstream address.
console.error("occupancy:", error);
return NextResponse.json({ error: "The counter could not be read." }, { status: 502 });
}
}Process lifetime. Nothing keeps running on the server between requests, so this works the
same on a long running server and on a serverless platform. A connection that must stay open
(an MQTT subscription, a webhook receiver filling a scene) needs a process that lives longer
than a request; the endpoint then returns that scene's latest reading,
scene.latest(id, quantity), instead of calling the system.
3. Read the endpoint in the browser and bind it
pollingSource calls read() every two seconds while the Connector is mounted, and stops when
it unmounts. The reading lands on the entrance because its binding names the same source and
entity. A failed read goes to onError; the page says so instead of showing the last value
without a word.
"use client";
import { useMemo, useState } from "react";
import { pollingSource } from "@klorad/api/integration";
import { Connector, KloradProvider, SceneObject, useLatest } from "@klorad/react";
import { ThreeView } from "@klorad/engine-three/react";
type Answer = { entity: string; value: number; unit: string; observedAt: number } | { error: string };
function Occupancy({ problem }: { problem: string | null }) {
const latest = useLatest("entrance", "occupancy");
if (problem && !latest) return <p>No reading yet: {problem}</p>;
return <p>{latest ? `${latest.value} ${latest.unit} at the entrance` : "Waiting for the first reading"}{problem ? ` (last read failed: ${problem})` : ""}</p>;
}
export default function ConnectedTwin() {
const [selected, setSelected] = useState<string | null>(null);
const [problem, setProblem] = useState<string | null>(null);
// The browser reads your own endpoint, never the counter: the credential stays on the server.
const source = useMemo(
() =>
pollingSource({
id: "gateway",
intervalMs: 2_000,
read: async () => {
const answer = (await (await fetch("/api/occupancy", { cache: "no-store" })).json()) as Answer;
if ("error" in answer) throw new Error(answer.error);
setProblem(null);
return [{ entity: answer.entity, quantity: "occupancy", value: answer.value, unit: answer.unit, observedAt: answer.observedAt }];
},
onError: (error) => setProblem(error instanceof Error ? error.message : String(error)),
}),
[],
);
return (
<KloradProvider options={{ coordinateSystem: { origin: { lat: 40.62637, lon: 22.94838 } }, staleAfterMs: 10_000 }}>
<SceneObject id="hall" name="Exhibition hall" position={{ east: 0, north: 0 }} geometry={{ kind: "box", width: 24, depth: 14, height: 7 }} />
<SceneObject
id="entrance"
name="Entrance counter"
position={{ east: 16, north: -10 }}
geometry={{ kind: "cylinder", radius: 2, height: 4 }}
correspondence="shadow"
binding={{ source: "gateway", entity: "entrance-01" }}
/>
{/* Polling starts when this mounts and stops when it unmounts. */}
<Connector source={source} />
<Occupancy problem={problem} />
<div style={{ height: 480 }}>
<ThreeView selected={selected} onPick={setSelected} />
</div>
</KloradProvider>
);
}4. Run it with test data
The starter serves a stand in for the counter's API at /api/demo-counter, which asks for the
same bearer token a real system would:
import { NextResponse } from "next/server";
// A stand in for your counter's API, so the connected page runs end to end without hardware.
// It asks for the same bearer token a real system would. Delete it when you point COUNTER_URL at your system.
export const dynamic = "force-dynamic";
export function GET(request: Request) {
if (request.headers.get("authorization") !== `Bearer ${process.env.COUNTER_TOKEN}`) {
return NextResponse.json({ error: "unauthorised" }, { status: 401 });
}
const people = 20 + (Math.floor(Date.now() / 1000) % 7);
return NextResponse.json({ device: "entrance-01", people, measuredAt: new Date().toISOString() });
}cp .env.example .env.local
npm run devOpen http://localhost:3100/connected. Expected result: the
hall and the counter in 3D, and a line such as "24 people at the entrance" that changes every
few seconds. Without .env.local the line reads "No reading yet: The counter could not be
read." and the server's console says why. If the counter stops answering for ten seconds, its
reading turns stale (staleAfterMs).
To connect your own counter, set COUNTER_URL and COUNTER_TOKEN to its address and token,
change the schema in lib/counter.ts to what it sends, and delete app/api/demo-counter.
What is checked
The docs build this starter in CI (pnpm check:starter), and their end to end check
(pnpm --filter @klorad/docs starter:verify) runs it: both pages show a reading in a browser, a
failed read is shown on the page, and neither the endpoint's answers nor the browser bundle
carry the credential.
Other transports
Polling an endpoint is the simplest path and adds a delay of up to one interval. For readings
the moment they arrive, push them to the browser over a WebSocket or server sent events from a
long running server, and give the browser a source of your own: an object with an id and a
start(sink) method (Integration). The scene, the binding and the
page stay as they are.
The connectors on the server side: Connect MQTT devices, Receive webhooks, Connect a polling API.
Something wrong or unclear? Tell us.
How your system connects
For a technology partner with equipment or a platform of its own, what connects to Klorad today, what the work is, and how we prove the connection.
Connect MQTT devices
Turn messages on an MQTT broker into readings for shadows and twins, and publish a twin's commands back to the device.