Triggering from your app
Realtime in the browser
Show a run's status, metadata and output live in a web page, with a public access token your server mints and the useRealtimeRun React hook.
On this page
A page can follow a run itself, without a relay on your server. Your server mints a public access token that reads only the runs it names, and the page hands that token to useRealtimeRun from @bokjoy/sdk/react. This is Trigger.dev's auth.createPublicToken and useRealtimeRun, with the same shapes. Your API key never leaves your server.
Mint a token on your server#
auth.createPublicToken asks the control plane for a token, with your API key:
// Run with: node public-token.mjs <run id>import { auth } from '@bokjoy/sdk'; // Reads this run and the runs it starts, for an hour, and nothing else.const publicToken = await auth.createPublicToken({ scopes: { read: { runs: [process.argv[2]] } }, expirationTime: '1h',});console.log(publicToken);# Run with: python public-token.py <run id>import sys from bokjoy import auth # Reads this run and the runs it starts, for an hour, and nothing else.public_token = auth.create_public_token( scopes={"read": {"runs": [sys.argv[1]]}}, expiration_time="1h",)print(public_token)| Option | Node | Python | Value |
|---|---|---|---|
| Runs | scopes: {read: {runs: [...]}} | scopes={"read": {"runs": [...]}} | The runs the token reads: run IDs or handles, at most 32 runs. Each must be in the key's environment. |
| Lifetime | expirationTime | expiration_time | A span such as '15m', '1h' or '2 hours'. Or a moment: a Date in Node, a timezone-aware datetime in Python, or a number of Unix seconds. |
A token lasts 15 minutes by default and 24 hours at most. A number is a moment, not a duration, as in Trigger.dev: expirationTime: 3600 is one hour after 1970, and is refused. Pass '1h' for an hour from now.
Trigger.dev's other scopes, read: {tasks}, {tags} and {batch}, and runs: true for every run, are refused with a ValidationError. A Bok Joy token only reads the runs you name.
A Next.js route#
Mint the token in a route that checks who is asking. This one, like the one Trigger.dev's docs show, answers POST /api/runs/<id>/token for a run the signed-in user owns:
import { auth } from '@bokjoy/sdk';import { NextResponse } from 'next/server';import { currentUser, ownsRun } from '@/lib/session'; export async function POST(_request: Request, { params }: { params: Promise<{ id: string }> }) { const { id } = await params; const user = await currentUser(); if (!user || !(await ownsRun(user, id))) { return NextResponse.json({ error: 'not found' }, { status: 404 }); } const publicToken = await auth.createPublicToken({ scopes: { read: { runs: [id] } }, expirationTime: '1h', }); return NextResponse.json({ publicToken });}currentUser and ownsRun stand for your own session and data checks. The shared auth reads BOKJOY_API_URL and BOKJOY_API_KEY from the server's environment, like tasks. With your own client, call client.auth.createPublicToken.
Rate-limit the route per user too. Every token you mint is a new one, so a user who keeps asking for tokens can use up your environment's share of streams and reads (Limits) for everyone else in it.
Follow the run in the page#
useRealtimeRun(runId, {accessToken}) returns {run, error}, and updates run on every change:
'use client';import { useRealtimeRun } from '@bokjoy/sdk/react'; type Progress = { processed: number; total: number }; export function useImportProgress(runId: string | null, accessToken: string | null) { const { run, error } = useRealtimeRun(runId, { accessToken: accessToken ?? undefined, enabled: Boolean(runId && accessToken), baseURL: process.env.NEXT_PUBLIC_BOKJOY_API_URL, onComplete: (finished) => console.log('import finished', finished.status), }); const progress = run?.metadata.progress as Progress | undefined; return { status: run?.status, progress, done: run?.isFinished ?? false, error };}The page asks your route for the token once it knows the run, for example after the form that triggered it:
const response = await fetch(`/api/runs/${runId}/token`, { method: 'POST' });const { publicToken } = await response.json();| Option | Default | Meaning |
|---|---|---|
accessToken | none | The public token. Nothing is followed without one, and an API key (bjk_...) is refused. |
enabled | true | Follow only while true. |
baseURL | https://api.bokjoy.dev | The control plane. https, or plain http only to this machine (localhost, 127.x.x.x or ::1), such as http://127.0.0.1:19847 in development. |
onComplete | none | Called once, with the finished run and its output. |
A new run ID, token or base URL starts over, and unmounting the component stops following. The hook reconnects by itself after a dropped connection, and reads the run afresh each time, so no change is missed or applied twice. error is set when the token is refused or expires, or the run is not one it grants, and then the hook stops. It is also set when connecting keeps failing, after five failed connections in a row or 15 seconds of them. The hook keeps retrying, waiting a little longer each time, and the error clears once a connection has worked for a few seconds. When a limit turns the hook away, error says which at once, and the hook waits longer before it tries again. stop(), also returned, stops early.
react is an optional peer dependency of @bokjoy/sdk, version 18 or later. Only @bokjoy/sdk/react imports it.
The run#
| Field | Value |
|---|---|
id, taskId | The run and its task. taskIdentifier is Trigger.dev's name for taskId. |
status | Trigger.dev's status, in upper case, as below. |
metadata | What the task set with ctx.metadata, {} until it sets any. See Live progress. |
milestones | The newest 20 milestones: name, progress, detail and at. |
output | The result once the run completed, else null. |
createdAt, updatedAt | Timestamps. |
isQueued, isExecuting, isWaiting | The run's state. |
isFinished | The run completed, failed or was cancelled. |
isCompleted | The run completed or failed, as in Trigger.dev's realtime runs. False for a cancelled run. |
isSuccess, isFailed, isCancelled | How it finished. isFailed is false for a cancelled run. |
useRealtimeRun uses Trigger.dev's upper case statuses, so code moved from @trigger.dev/react-hooks keeps its comparisons. The server SDK's runs.retrieve keeps Bok Joy's own lower case ones.
| Bok Joy status | run.status |
|---|---|
queued | QUEUED |
running | EXECUTING |
waiting | WAITING |
completed | COMPLETED |
failed | FAILED |
cancelled | CANCELED |
The run has no payload, error text, attempts, logs or anything about where it ran. A page that needs one of those should ask your server.
What a public token can read#
A public token, bjp_..., reads the runs it names and every run they start, in the environment of the key that minted it, until it expires. It can do two things:
GET /v1/runs/{id}, which answers aPublicRun: the fields above, without the payload, error text or attempts. A hook run answersoutput: null, since its output holds what its hooks threw.GET /v1/runs/{id}/stream, the run stream, with the same parts left out: snapshots list no attempts or error text, and onlyrun.created,run.status,metadataandmilestoneevents are sent. When the token expires, the stream closes with code 1008.
Everything else answers 403: triggering, cancelling, sending events, listing runs, and a run the token does not name or descend from. An expired token, and one whose API key was revoked, answer 401. A stream already open with the token closes with code 1008 within 15 seconds of its API key being revoked, though messages already on their way may still arrive. A token is signed with a key only the control plane holds, so it cannot be changed to name other runs.
Both routes answer browsers on other origins, for a public token only: an API key in a page's request still gets no cross-origin answer. A browser cannot set headers on a WebSocket, so the page offers the token as a subprotocol, bokjoy.token.<token>, beside bokjoy.stream.v1. It never goes in the URL, where it would land in server logs. The hook does all of this.
The token is signed, not encrypted: whoever holds it can read the run IDs and environment it names, when it expires, the ID of the key that signed it, and the ID of the API key that minted it. That ID is the middle part of your bjk_ key, not its secret, and it cannot call the API. Treat the token as a short-lived read credential for those runs.
Limits#
| Limit | Per token | Per environment |
|---|---|---|
| Open streams | 4 of each run it names | 128 |
| Stream opens | 32 at once, then 2 a second | 128 at once, then 32 a second |
| Reads of a run | 64 at once, then 4 a second | 256 at once, then 128 a second |
Four streams of a run cover a few tabs on it. A token that names several runs follows each of them. 128 is the most pages one environment can have following runs at once, production included, and the control plane holds 512 public streams in all.
Past a stream limit, the stream opens and closes at once with code 1013 and a reason naming the limit, which the hook shows in error. Past a read limit, the read answers 429 with Retry-After. Public streams have their own share of the control plane, so a busy page never keeps your API keys from following runs.
Without React#
The hook is the only browser client. From other code, read the run with the token as a bearer token, and follow it with the token as a subprotocol:
const base = 'https://api.bokjoy.dev';const response = await fetch(`${base}/v1/runs/${runId}`, { headers: { authorization: `Bearer ${publicToken}` },});const run = await response.json(); const socket = new WebSocket(`${base.replace('https', 'wss')}/v1/runs/${runId}/stream`, [ 'bokjoy.stream.v1', `bokjoy.token.${publicToken}`,]);socket.onmessage = (message) => console.log(JSON.parse(message.data));The messages are the run stream's, with the parts above left out. After a dropped connection, reconnect without a cursor: the new snapshot carries the current state.