Skip to content

Guides

Next.js

Start Bok Joy runs from a Next.js App Router app with Server Actions, and show them live with a Route Handler that relays the run stream to the browser.

On this page

This guide walks through the Next.js starter in examples/nextjs-starter of the Bok Joy repository. It is an App Router app with its tasks beside it, in bokjoy/:

TaskKindWhat it shows
welcome.sendTaskA payload in, a result out, triggered with an idempotency key.
report.generateWorkflowA child task per section, a durable sleep, and live metadata and milestones.
approval.waitWorkflowA wait for an event, which the app sends when you click Approve.

Every code block below is a file of the starter, as it is in the repository.

Install#

You need Node 24 or later, Docker, and Rust with Cargo. From the checkout's root, start the local Postgres, resolve the base images and build the CLI, as in the Quickstart. Then install the starter:

Terminal
cd examples/nextjs-starternpm install

The app depends on the SDK by its folder in the checkout. Its .npmrc sets install-links=true, so npm copies the folder into node_modules instead of linking it there: Next.js's bundler does not follow a link to a folder outside the project, and the build fails with Can't resolve '@bokjoy/sdk'. Run npm install again after you update the checkout.

package.json
{  "name": "bokjoy-nextjs-starter",  "version": "0.1.0",  "private": true,  "type": "module",  "scripts": {    "dev": "next dev",    "build": "next build",    "start": "next start",    "typecheck": "next typegen && tsc --noEmit",    "test": "node --test test/",    "test:e2e": "node --test --test-concurrency=1 e2e/",    "bokjoy:serve": "node scripts/bokjoy.mjs serve",    "bokjoy:deploy": "node scripts/bokjoy.mjs deploy"  },  "dependencies": {    "@bokjoy/sdk": "file:../../sdk/node",    "next": "16.4.0",    "react": "19.3.0",    "react-dom": "19.3.0",    "server-only": "^0.0.1"  },  "devDependencies": {    "@types/node": "^24",    "@types/react": "^19",    "@types/react-dom": "^19",    "playwright": "^1.64.0",    "typescript": "^5"  },  "engines": {    "node": ">=24"  }}

The tasks#

bokjoy/ is a task project (Deploying): a manifest and the handlers. The bokjoy:serve and bokjoy:deploy scripts copy the installed SDK into bokjoy/sdk/ first, since a deployment bundles the SDK's runner from there.

bokjoy/manifest.json
{  "tasks": [    {"id": "welcome.send", "kind": "task", "runtime": "node",     "entrypoint": "tasks/welcome.ts", "handler": "sendWelcome",     "compute": {"machine": "micro", "timeout_ms": 30000},     "max_attempts": 3},    {"id": "report.generate", "kind": "workflow", "runtime": "node",     "entrypoint": "tasks/report.ts", "handler": "generateReport",     "compute": {"machine": "micro", "timeout_ms": 30000},     "max_attempts": 3},    {"id": "report.section", "kind": "task", "runtime": "node",     "entrypoint": "tasks/report.ts", "handler": "writeSection",     "compute": {"machine": "micro", "timeout_ms": 30000},     "max_attempts": 3},    {"id": "approval.wait", "kind": "workflow", "runtime": "node",     "entrypoint": "tasks/approval.ts", "handler": "waitForApproval",     "compute": {"machine": "micro", "timeout_ms": 30000},     "max_attempts": 3}  ]}

The tasks are TypeScript. Node 24 strips the types and runs them as they are, so they need no build step, and import type keeps the SDK out of the bundle. A plain task takes a payload and returns its result:

bokjoy/tasks/welcome.ts
import type { Context } from '@bokjoy/sdk'; export type Welcome = {  name: string;  email: string;}; // A plain task: it takes a payload and returns a result. Bok Joy// retries a failed attempt up to max_attempts, so pass// ctx.idempotencyKey to your email provider to send only once.export async function sendWelcome(payload: Welcome, ctx: Context) {  if (!payload?.name || !payload?.email) {    throw new Error('name and email are required');  }  const subject = `Welcome aboard, ${payload.name}!`;  console.log(`send "${subject}" to ${payload.email}`, ctx.idempotencyKey);  return { sent: true, to: payload.email, subject };}

The report is a workflow. It calls report.section once per section, then sleeps, and reports live progress on the way. Each ctx.callTask and ctx.sleep suspends the workflow, and it replays from the top when the step is done, so the side effects live in the child task:

bokjoy/tasks/report.ts
import type { Context } from '@bokjoy/sdk'; export type ReportRequest = {  topic: string;  sections: number;}; export type Section = {  index: number;  title: string;  words: number;}; // A workflow: every awaited ctx call is a recorded step. A new step// ends the attempt, and the workflow runs again from the top once// the step is done, replaying recorded steps instantly. Metadata// and milestones stream to the app live, and a replay never sends// them twice.export async function generateReport(input: ReportRequest, ctx: Context) {  const count = Math.min(Math.max(Math.trunc(input.sections) || 3, 1), 5);  ctx.metadata.set('topic', input.topic);  ctx.metadata.set('sections', count);  ctx.metadata.set('written', 0);  ctx.milestone('Outline ready', {    progress: 0.1,    detail: `${count} sections`,  });   const sections: Section[] = [];  for (let index = 1; index <= count; index++) {    const section = (await ctx.callTask(      'report.section',      { topic: input.topic, index },      `section-${index}`,    )) as Section;    sections.push(section);    ctx.metadata.set('written', index);    ctx.milestone(`Section ${index} written`, {      progress: 0.1 + (0.7 * index) / count,      detail: section.title,    });  }   // A durable timer. No worker is held while it waits.  await ctx.sleep(3_000, 'review');  ctx.milestone('Reviewed and published', { progress: 1 });   const words = sections.reduce((sum, section) => sum + section.words, 0);  return { topic: input.topic, titles: sections.map((s) => s.title), words };} // The child task each section runs as. Side effects, such as an LLM// call, belong here rather than in the workflow, which replays.export async function writeSection(input: {  topic: string;  index: number;}): Promise<Section> {  await new Promise((resolve) => setTimeout(resolve, 1_500));  return {    index: input.index,    title: `${input.topic}, part ${input.index}`,    words: 180 + input.index * 40,  };}

Run it locally#

In the terminal where you built the CLI, start a control plane with the starter's manifest, and leave it running:

Terminal
npm run bokjoy:serve

In a second terminal, create a key for dev, and copy the example environment file:

Terminal
cd examples/nextjs-starter../../target/debug/durable-compute api-keys create --env dev --name nextjs-startercp .env.example .env.local

Put the token from the answer in .env.local as BOKJOY_API_KEY:

.env.example
# Copy to .env.local. Next.js reads it on the server only: neither# variable has the NEXT_PUBLIC_ prefix, so neither reaches the browser. # The control plane. A local one from `npm run bokjoy:serve` listens on# http://127.0.0.1:19847. The hosted alpha is https://api.bokjoy.dev.BOKJOY_API_URL=http://127.0.0.1:19847 # An environment API key, bjk_<env>_... It decides the environment that# runs start in. Create one for a local control plane with:#   durable-compute api-keys create --env dev --name nextjs-starterBOKJOY_API_KEY=

Then start the app and open http://localhost:3000:

Terminal
npm run dev

Trigger from a Server Action#

Each form on the home page posts to a Server Action. The action calls tasks.trigger and redirects to the run's page:

app/actions.ts
'use server'; import { redirect } from 'next/navigation'; import type { waitForApproval } from '@/bokjoy/tasks/approval';import type { generateReport } from '@/bokjoy/tasks/report';import type { sendWelcome } from '@/bokjoy/tasks/welcome';import {  bokjoy,  describeProblem,  isRunId,  sendEvent,  type Problem,} from '@/lib/bokjoy'; // Server Actions run on the server, so the API key stays there. Each// one is also a public HTTP endpoint: in your app, check the user's// session here before starting a run on their behalf. export type ActionState = { problem?: Problem; done?: string } | null; export async function startWelcome(_: ActionState, form: FormData) {  const name = field(form, 'name', 80);  const email = field(form, 'email', 100);  if (!name || !email) {    return problem('Missing details', 'Enter a name and an email.');  }  // `typeof sendWelcome` types the payload. The idempotency key makes  // a second welcome to the same email return the first run.  return start(() =>    bokjoy().tasks.trigger<typeof sendWelcome>(      'welcome.send',      { name, email },      { idempotencyKey: `welcome:${email}` },    ),  );} export async function startReport(_: ActionState, form: FormData) {  const topic = field(form, 'topic', 80) || 'Bees';  const sections = Number(form.get('sections')) || 3;  return start(() =>    bokjoy().tasks.trigger<typeof generateReport>('report.generate', {      topic,      sections,    }),  );} export async function startApproval(_: ActionState, form: FormData) {  const request = field(form, 'request', 200) || 'Ship the new pricing page';  return start(() =>    bokjoy().tasks.trigger<typeof waitForApproval>('approval.wait', {      request,    }),  );} /** Sends the event approval.wait is waiting for. */export async function decide(  runId: string,  _: ActionState,  form: FormData,): Promise<ActionState> {  if (!isRunId(runId)) return problem('Not a run', 'That is not a run ID.');  const approved = form.get('decision') === 'approve';  try {    // One decision per run: resending it is a no-op, and a different    // second one is a conflict.    await sendEvent(runId, {      id: `approval:${runId}`,      name: 'approval',      payload: { approved, by: 'the starter app' },    });  } catch (error) {    return failed(error);  }  return { done: `${approved ? 'Approved' : 'Rejected'}. It resumes now.` };} /** Starts a run, then shows its page, or the problem on the form. */async function start(  trigger: () => Promise<{ id: string }>,): Promise<ActionState> {  let id: string;  try {    id = (await trigger()).id;  } catch (error) {    return failed(error);  }  // Outside the try: redirect() works by throwing.  redirect(`/runs/${id}`);} function field(form: FormData, name: string, max: number): string {  return String(form.get(name) ?? '')    .trim()    .slice(0, max);} function problem(title: string, detail: string): ActionState {  return { problem: { title, detail } };} function failed(error: unknown): ActionState {  console.error(error);  return { problem: describeProblem(error) };}
  • The payload is typed. tasks.trigger<typeof sendWelcome> checks the payload against the handler's first parameter, so a wrong field fails next build. The import is type only: none of the task's code loads into the app. See Typed payloads.
  • The same email returns the same run. The idempotency key is welcome:<email>, so a second submit finds the first run, and the same key with another name is a ConflictError. See Idempotency.
  • redirect stays outside the try. It works by throwing, and a catch would swallow it.

lib/bokjoy.ts makes the client from BOKJOY_API_URL and BOKJOY_API_KEY, and turns each SDK error into a message for the form. It imports server-only, so a Client Component that imports it fails the build, and the key can never reach the browser:

lib/bokjoy.ts
import 'server-only'; import {  ApiConnectionError,  AuthenticationError,  BokJoy,  BokJoyError,  ConflictError,  NotFoundError,  PermissionDeniedError,  ValidationError,  type JSONValue,} from '@bokjoy/sdk'; // Everything that talks to Bok Joy lives on the server. `server-only`// makes the build fail if a Client Component imports this file, so the// API key can never end up in the browser's JavaScript. export type Problem = { title: string; detail: string }; /** The two variables the app needs, or the names of those that are unset. */export function readSetup():  { ok: true; url: string; apiKey: string } | { ok: false; missing: string[] } {  const url = process.env.BOKJOY_API_URL;  const apiKey = process.env.BOKJOY_API_KEY;  if (url && apiKey) return { ok: true, url, apiKey };  const missing = [];  if (!url) missing.push('BOKJOY_API_URL');  if (!apiKey) missing.push('BOKJOY_API_KEY');  return { ok: false, missing };} class SetupError extends Error {  readonly missing: string[];  constructor(missing: string[]) {    super(`${missing.join(' and ')} not set`);    this.missing = missing;  }} /** * A client for the configured control plane and key. Passing both in * code means the SDK never falls back to its older DC_API_URL and * DC_API_TOKEN variables, which may hold an operator token. */export function bokjoy(): BokJoy {  const { url, apiKey } = requireSetup();  return new BokJoy({ url, apiKey });} function requireSetup(): { url: string; apiKey: string } {  const setup = readSetup();  if (!setup.ok) throw new SetupError(setup.missing);  return setup;} const RUN_ID =  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export function isRunId(value: string): boolean {  return RUN_ID.test(value);} /** * Sends a named event to a run, which a workflow waiting in * ctx.waitEvent receives. The SDK has no call for this yet, so it is * one POST with the same URL and key. `id` deduplicates: sending the * same event again is a no-op. */export async function sendEvent(  runId: string,  event: { id: string; name: string; payload: JSONValue },): Promise<void> {  const { url, apiKey } = requireSetup();  // A client checks the URL: https, or plain http only to this machine.  new BokJoy({ url, apiKey });  const path = `/v1/runs/${runId}/events`;  let response: Response;  try {    response = await fetch(url.replace(/\/+$/, '') + path, {      method: 'POST',      headers: {        authorization: `Bearer ${apiKey}`,        'content-type': 'application/json',      },      body: JSON.stringify({        event_id: event.id,        name: event.name,        payload: event.payload,      }),      // A redirect would carry the key to wherever it points.      redirect: 'manual',      signal: AbortSignal.timeout(10_000),    });  } catch (error) {    throw new ApiConnectionError(      `POST ${path}: could not reach the control plane at ${url}`,      { cause: error },    );  }  if (response.ok) return;  const text = await response.text();  let reason = text || `HTTP ${response.status}`;  try {    reason = JSON.parse(text).error ?? reason;  } catch {}  const message = `POST ${path}: ${reason}`;  if (response.status === 401) throw new AuthenticationError(message);  if (response.status === 404) throw new NotFoundError(message);  if (response.status === 409) throw new ConflictError(message);  if (response.status < 400)    throw new ApiConnectionError(      `${message}: the control plane answered with a redirect`,    );  if (response.status < 500) throw new ValidationError(message);  throw new BokJoyError(message);} /** A message for the page. It never contains the API key: neither do SDK errors. */export function describeProblem(error: unknown): Problem {  const detail = error instanceof Error ? error.message : String(error);  if (error instanceof SetupError) {    return {      title: 'Bok Joy is not set up',      detail: `Set ${error.missing.join(' and ')} in .env.local (see .env.example), then restart the app.`,    };  }  if (error instanceof AuthenticationError) {    return {      title: 'The API key was refused',      detail:        'Check BOKJOY_API_KEY: it is mistyped, revoked, or from another control plane.',    };  }  if (error instanceof PermissionDeniedError) {    return { title: 'The API key may not do this', detail };  }  if (error instanceof ApiConnectionError) {    return {      title: 'Bok Joy is unreachable',      detail: `${detail}. Check that the control plane is running and that BOKJOY_API_URL points at it.`,    };  }  if (error instanceof NotFoundError) {    return {      title: 'Not found',      detail: 'There is no such run in the environment of this API key.',    };  }  if (error instanceof ConflictError) {    return { title: 'Bok Joy refused this as a conflict', detail };  }  if (error instanceof ValidationError) {    // Includes a bad BOKJOY_API_URL, and a task the deployment lacks.    return { title: 'Bok Joy refused the request', detail };  }  if (error instanceof BokJoyError) {    return { title: 'Bok Joy answered with an error', detail };  }  // The run stream's own errors are plain Errors, such as a refused key.  return { title: 'Something went wrong', detail };}

It passes the URL and key to new BokJoy in code. The SDK then never falls back to the older DC_API_URL and DC_API_TOKEN variables, which may hold an operator token on a developer's machine.

Show the run live#

The run stream authenticates with your API key, and the SDK follows it over a WebSocket from Node, so it belongs on your server (Read, cancel and follow runs). The starter follows it in a Route Handler and relays it to the browser as Server-Sent Events:

app/api/runs/[id]/stream/route.ts
import { bokjoy, describeProblem, isRunId } from '@/lib/bokjoy';import {  applyMessage,  fromRun,  isFinished,  type RunView,} from '@/lib/run-view'; // Follows a run on the server with the SDK's run stream, and relays it// to the browser as Server-Sent Events. Each `run` event carries the// whole view, so a browser that reconnects just starts over. The key// never leaves the server.////   event: run      data: RunView, after every change//   event: problem  data: {title, detail}, then the stream ends//   event: end      data: {}, once the run and its children settled const KEEP_ALIVE_MS = 15_000; export async function GET(  request: Request,  ctx: RouteContext<'/api/runs/[id]/stream'>,) {  const { id } = await ctx.params;  if (!isRunId(id))    return Response.json({ error: 'not a run ID' }, { status: 404 });   // Stops the subscription when the browser leaves, however Next.js  // reports it: an aborted request or a cancelled body.  const stop = new AbortController();  request.signal.addEventListener('abort', () => stop.abort());  const body = new ReadableStream<Uint8Array>({    start(controller) {      // Not awaited, so the response starts at once.      void relay(id, controller, stop.signal);    },    cancel() {      stop.abort();    },  });   return new Response(body, {    headers: {      'content-type': 'text/event-stream; charset=utf-8',      // no-transform keeps compression from buffering the events.      'cache-control': 'no-cache, no-transform',      'x-accel-buffering': 'no',    },  });} async function relay(  id: string,  controller: ReadableStreamDefaultController<Uint8Array>,  signal: AbortSignal,) {  const encoder = new TextEncoder();  const write = (text: string) => {    if (!signal.aborted) controller.enqueue(encoder.encode(text));  };  const send = (event: string, data: unknown) =>    write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);  // A comment now and then keeps proxies from closing a quiet stream.  const keepAlive = setInterval(() => write(': keep-alive\n\n'), KEEP_ALIVE_MS);   try {    const client = bokjoy();    let view: RunView = fromRun(await client.runs.retrieve(id, { signal }));    let resultRead = isFinished(view.status);    send('run', view);    for await (const message of client.runs.subscribe(id, { signal })) {      view = applyMessage(view, message);      if (isFinished(view.status) && !resultRead) {        // The stream carries no output: read the finished run once for        // it, so a finished view always arrives with its result.        const run = await client.runs.retrieve(id, { signal });        view = {          ...view,          status: run.status,          error: run.error,          output: run.output,        };        resultRead = true;      }      if (message.type !== 'end') send('run', view);    }    if (isFinished(view.status)) send('end', {});  } catch (error) {    if (!signal.aborted) {      console.error(error);      send('problem', describeProblem(error));    }  } finally {    clearInterval(keepAlive);    try {      controller.close();    } catch {      // The browser already went away.    }  }}
  • Each event is the whole view. lib/run-view.ts folds the stream's snapshot and events into the run's status, metadata, milestones and child runs, and the handler sends the result after every change. A browser that reconnects starts over from a fresh snapshot and misses nothing.
  • The output comes from runs.retrieve. The stream carries status, metadata and milestones but not the result, so the handler reads the run once more when it finishes, before it sends the finished view.
  • It stops when the browser leaves. Closing the page aborts the request, which closes the subscription to Bok Joy.

The browser only ever talks to the app. The run page reads the run on the server first, so a bad key or an unknown run shows at once, then follows the route with an EventSource:

app/runs/[id]/use-run-stream.ts
'use client'; import { useEffect, useState } from 'react'; import type { Problem } from '@/lib/bokjoy';import type { RunView } from '@/lib/run-view'; export type Connection = 'connecting' | 'live' | 'finished' | 'stopped'; /** * Follows a run through the app's own stream route, never Bok Joy * directly: the browser holds no key. EventSource reconnects by itself * after a drop, and each `run` event is the whole view, so nothing is * lost in between. */export function useRunStream(initial: RunView) {  const [view, setView] = useState(initial);  const [problem, setProblem] = useState<Problem | null>(null);  const [connection, setConnection] = useState<Connection>('connecting');   useEffect(() => {    const source = new EventSource(`/api/runs/${initial.id}/stream`);    source.addEventListener('open', () => setConnection('live'));    source.addEventListener('run', (event) => {      setView(JSON.parse(event.data));      setProblem(null);    });    source.addEventListener('end', () => {      source.close();      setConnection('finished');    });    source.addEventListener('problem', (event) => {      source.close();      setProblem(JSON.parse(event.data));      setConnection('stopped');    });    // A dropped connection: EventSource retries on its own.    source.addEventListener('error', () => {      if (source.readyState !== EventSource.CLOSED) setConnection('connecting');    });    return () => source.close();  }, [initial.id]);   return { view, problem, connection };}

Send an event#

approval.wait waits for an event named approval, for up to ten minutes. While it waits, the run is waiting and holds no worker:

bokjoy/tasks/approval.ts
import type { Context } from '@bokjoy/sdk'; export type ApprovalRequest = {  request: string;}; export type Decision = {  approved: boolean;  by: string;}; type Wait = { timed_out: boolean; payload: Decision | null }; // A workflow that waits for an event, here a person's decision. The// app sends it to this run by ID. While it waits, the run is// `waiting` and holds no worker, for up to the timeout.export async function waitForApproval(input: ApprovalRequest, ctx: Context) {  ctx.metadata.set('request', input.request);  ctx.milestone('Waiting for a decision', { progress: 0.5 });   const wait = (await ctx.waitEvent(    'approval',    10 * 60_000,    'approval',  )) as Wait;  if (wait.timed_out || !wait.payload) {    ctx.milestone('No decision in 10 minutes', { progress: 1 });    return { approved: false, timedOut: true };  }   const { approved, by } = wait.payload;  ctx.metadata.set('decidedBy', by);  ctx.milestone(approved ? 'Approved' : 'Rejected', { progress: 1 });  return { approved, timedOut: false };}

The run page shows Approve and Reject while the run is unfinished. Both call the decide action above, which sends the event with sendEvent from lib/bokjoy.ts. The SDKs have no call for events yet, so it posts to /v1/runs/{id}/events with the same URL and key. The event's ID is approval:<run id>, so a resent event is a no-op, and a different second answer is a conflict.

Errors#

What went wrongWhat the app shows
BOKJOY_API_URL or BOKJOY_API_KEY is not setThe home page names the missing variable, and so does a form you submit.
The key is wrong or revokedThe API key was refused.
The control plane is down, or the URL is wrongBok Joy is unreachable, with the URL and the reason.
The environment's deployment lacks the taskBok Joy refused the request, with the control plane's reason.
The run does not exist, or is in another environmentNot found, on the run page.

Errors lists every class the SDK throws.

Deploy#

The app and its tasks deploy separately. To deploy the tasks with database access to a control plane, run:

Terminal
npm run bokjoy:deploy -- --env staging

It builds an image, registers the deployment and makes it current in staging. Give the app a staging key and its runs use the new code. Promote the same deployment to prod later with no rebuild (Deploying).

On Vercel, set BOKJOY_API_URL to https://api.bokjoy.dev and BOKJOY_API_KEY to a key for the environment the app should use. Vercel builds from the project's root directory, but the SDK's folder is outside it, so pack the SDK into the project and commit the tarball:

Terminal
npm pack ../../sdk/node --pack-destination vendornpm install ./vendor/bokjoy-sdk-0.1.0.tgz

package.json then depends on file:vendor/bokjoy-sdk-0.1.0.tgz, with its hash in the lockfile, and Vercel installs it like any package. Once the SDK is on npm, depend on its version instead, and delete .npmrc and the tarball. Nothing else changes.

Test it#

npm test runs each task through the SDK's task runner, as a worker does, with no control plane. npm run test:e2e drives the app in Chromium against a running control plane: all three tasks, live updates without a reload, a check that no response holds the API key, and each error above.