JavaScript client
Follow runs and streams from Vue, Svelte, plain JavaScript, or Node.js.
Use the JavaScript client when you are not using React. It works in browsers and in Node.js 22.18 or later. The React hooks use this same client inside.
Install
npm install @runlane/realtimeCreate a client
Create one client and reuse it for every run.
import { createRunlaneClient } from '@runlane/realtime/client'
export const client = createRunlaneClient({
baseUrl: 'https://app.example.com/api/progress',
})baseUrl must be a full http or https URL. It is the path where you mounted the handler. It cannot contain a query, a fragment, or a user name and password.
| Option | Meaning |
|---|---|
baseUrl | Required. The handler's full URL. |
refreshAccessToken | Optional. Returns a fresh token for a run. See refresh expired tokens. |
fetch | Optional. A custom fetch function. |
telemetry, onTelemetryError | Optional. Record client metrics. See telemetry. |
Follow a run
client.subscribe() returns an async iterator. Read it with for await.
import { RunSubscriptionEventType } from '@runlane/realtime/client'
import type { writeAnswer } from './tasks/write-answer'
const controller = new AbortController()
for await (const event of client.subscribe<typeof writeAnswer>(runId, { signal: controller.signal })) {
switch (event.type) {
case RunSubscriptionEventType.Snapshot:
showStatus(event.run.status)
break
case RunSubscriptionEventType.Status:
showStatus(event.status)
if (event.output) showResult(event.output)
break
case RunSubscriptionEventType.Meta:
showProgress(event.patch)
break
}
}- The
snapshotevent has the whole run. Later events are changes. Apply events in the order they arrive. - For a run that is still going, the snapshot comes first. For a run that already finished, saved stream records come first, then the snapshot and the final status.
- A reader started with
aftergets no snapshot. It continues from that cursor. - The loop ends on its own when the run finishes.
To get only status, metadata, and output, pass streams: false. The server then sends no stream records on this connection:
client.subscribe(runId, { streams: false, signal })Use readStream() for stream data instead. useRun works this way.
See the run object for each event's fields.
Read a stream
client.readStream() reads one named stream. It sends every saved part first, then new parts as the task writes them.
import { RunStreamRecordType } from '@runlane/realtime/client'
let text = ''
for await (const record of client.readStream<typeof writeAnswer>(runId, 'answer', { signal })) {
if (record.type === RunStreamRecordType.AttemptStarted) text = ''
if (record.type === RunStreamRecordType.Chunk) text += record.value
render(text)
}Each record has a type:
type | Meaning |
|---|---|
attempt_started | A new attempt started. Clear the old text if you only show the newest attempt. |
chunk | One part. Its data is in value. |
attempt_closed | The attempt stopped writing. reason says why, such as completed or failed. |
Every record also has attempt, the attempt number. The loop ends when the run finishes and all parts are delivered.
Stop reading
Pass an AbortSignal, then abort it when the view closes:
const controller = new AbortController()
void follow(controller.signal)
// Later, when the user leaves the page:
controller.abort()Aborting ends the loop quietly. It does not throw, and it does not cancel the run.
Send a token
Pass a token for the first connection with accessToken:
client.subscribe(runId, { accessToken, signal })Add refreshAccessToken to the client to get new tokens when one expires. With neither option, the client sends no token. It relies on same-origin cookies.
Show connection state
Pass onConnectionChange to either reader:
client.subscribe(runId, {
signal,
onConnectionChange(change) {
if (change.state === 'reconnecting') showBanner(`Reconnecting (try ${change.attempt})…`)
if (change.state === 'open') hideBanner()
},
})| State | When |
|---|---|
connecting | Before each connection try |
open | The connection is open and data can flow |
reconnecting | The connection failed. attempt counts tries, and delayMs is the wait before the next one. |
closed | The reader ended. reason is completed, aborted, or failed. A failed close also has error. |
If this callback throws, the reader stops.
Reconnects
The client reconnects on its own after a network drop, a server restart, or a busy server. It continues from the last event it delivered, so nothing repeats or goes missing.
It retries connection loss until you abort the reader. The default reconnect policy uses maxRetries: 'unlimited' and exponential backoff from 250ms to 10s, with random jitter. contractDefaults.realtime.reconnect owns these defaults. Authentication, bad requests, and other non-retryable errors still stop at once.
Set reconnect: { maxRetries: 5, backoff: { type: RetryBackoffType.Exponential, delay: '500ms', maxDelay: '30s' } } in createRunlaneClient(). Import RetryBackoffType from @runlane/contracts/realtime. A non-negative maxRetries counts retries after the first request; zero disables retries. Omit either field to use its default. Progress or a healthy idle connection resets the consecutive-failure count.
React users can pass reconnect to RunlaneProvider, or create a client with this option and pass it as client to the hooks. An equal inline policy keeps readers open across renders. Changing the policy creates a new client and restarts its readers.
Errors
When a reader fails, the loop throws a RunlaneError:
import { ErrorCode, RunlaneError } from '@runlane/realtime/client'
try {
for await (const event of client.subscribe(runId, { signal })) apply(event)
} catch (error) {
if (error instanceof RunlaneError && error.code === ErrorCode.AccessDenied) showSignIn()
else showMessage('Live updates stopped.')
}| Code | Meaning | Retried for you? |
|---|---|---|
access_denied | Not allowed to read this run, or the token could not be refreshed | Once, with a fresh token, if refreshAccessToken is set |
run_not_found | The run does not exist, or it was pruned | No |
validation_failed | The run ID or stream name is not valid | No |
run_cursor_invalid | The after cursor is not valid for this reader | No |
disconnected | A configured finite retry limit was reached | Increase reconnect.maxRetries, or use the unlimited default. |
wire_invalid | The response was not from the realtime handler. Check baseUrl. | No |
A failed run is not an error. It arrives as a status event with status: 'failed'.
See the realtime reference for every code.
Resume later
Every subscribe() event has a cursor. To continue in a new reader, pass the last cursor you handled as after:
client.subscribe(runId, { after: savedCursor, signal })A cursor belongs to one run and one reader type. Do not pass a subscribe() cursor to readStream(). While a reader stays open, the client tracks its cursor for you.