Skip to Content
Runlane
ReferenceApplication API

Realtime

Look up the realtime handler, scoped tokens, browser client, type helpers, errors, and wire limits.

This page lists the exact behavior of @runlane/realtime. To set it up, start with the realtime guides.

Imports

Import fromUse inMain exports
@runlane/realtimeServer codecreateRunlaneRealtime, and the types RunlaneRealtime, RunlaneRealtimeOptions, RunlaneRealtimeAuthorize, RunlaneRealtimeTokenOptions, CreateRealtimeTokenOptions, and RunlaneRealtimeSource. Also re-exports RunlaneError, ErrorCode, RunReadPermission, RunAccessGrant, and VerifiedRunToken.
@runlane/realtime/clientBrowsers and Node.js 22.18 or latercreateRunlaneClient, RunlaneError, ErrorCode, RunSubscriptionEventType, RunStreamRecordType, the client types, and the frontend type helpers
@runlane/contracts/realtimeBothShared schemas, enums, and types, plus realtimeDefaults

The client needs a browser with Fetch response streaming, or Node.js 22.18 or later.

Server entry

createRunlaneRealtime(options) returns a RunlaneRealtime:

MemberType
handle(request: Request) => Promise<Response>
createToken(options: CreateRealtimeTokenOptions) => Promise<string>
import { createRunlaneRealtime } from '@runlane/realtime'

export const realtime = createRunlaneRealtime({
  runlane,
  authorize,
  tokens: { audience: 'web', keyId: 'v1', key, verifyKeys: { v0: previousKey } },
})
export const GET = realtime.handle

Options

OptionMeaning
runlaneRequired. A RunlaneRealtimeSource. A core runtime works.
authorizeYour access check. See authorize.
tokensToken signing settings. See token options.
telemetry, onTelemetryErrorOptional. See telemetry.

You must set authorize, tokens, or both:

  • authorize alone suits same-origin session cookies.
  • tokens alone suits bearer tokens from a frontend on another origin.
  • Both check the token and your current policy on every connection.

Setting neither throws at construction. The message shows both fixes. Unknown options, or an authorize that is not a function, throw configuration_invalid. All of these checks run before the first request.

RunlaneRealtimeSource is a structural interface. It needs environment, runs.get(), runs.subscribe(), and runs.readStream(). It can also expose lane.runSignal, which wakes named stream readers sooner. A core runtime has all of these.

The handler starts no worker. A runtime that does not mount it does no extra storage reads or writes and needs no extra indexes.

Routes

The handler serves two routes. It matches the end of the path, so any prefix works without rewriting the URL. For example, mount it at /api/progress.

RouteResponse body
GET /runs/:id/eventsA run snapshot, then status, metadata, and permitted stream events
GET /runs/:id/streams/:nameSaved records for one stream, then new records and attempt closes
  • URI-encode run IDs and stream names.
  • Other methods return 405 with Allow: GET. Unknown routes return 404.
  • Send a resume cursor in Last-Event-ID or the after query parameter. Sending two different cursors returns 400.
  • The events route also accepts streams=none. It sends no stream records, whatever the grant allows. The client sends it for subscribe(runId, { streams: false }). Any other value, a repeated parameter, or streams on a stream route returns 400.
  • Any other query parameter returns 400.
  • A cursor is tied to one reader kind, environment, run, and retained run instance. It grants no access.
  • Run IDs and stream names cannot be . or .., because URL parsing removes those path segments. Their schemas reject them with a clear message. Generated run IDs always work.

Authorization

authorize

RunlaneRealtimeAuthorize is the type of the authorize option. It equals NonNullable<RunlaneRealtimeOptions['authorize']>. Use it to type a policy that lives in its own module.

type RunlaneRealtimeAuthorize = (input: {
  request: Request
  runId: RunId
  token?: VerifiedRunToken
}) => RunAccessGrant | undefined | Promise<RunAccessGrant | undefined>
  • It runs on every connection. It runs after token checks and before any run data is read.
  • Return a grant to allow access. Return undefined to deny it.
  • If it throws, the reader gets a safe 500 response.

Grants

import { RunReadPermission, type RunAccessGrant } from '@runlane/contracts/realtime'

const progressGrant: RunAccessGrant = {
  permissions: [RunReadPermission.Status, RunReadPermission.Meta, RunReadPermission.Streams],
  streams: ['answer'],
}
PermissionSends
StatusRun snapshots and status changes
MetaMetadata patches. Snapshot metadata also needs Status.
Outputoutput and failure inside permitted snapshots and status changes
StreamsStream records, limited to streams when you set it

Name rules:

  • Leaving out streams allows every name, but only with the Streams permission.
  • streams: [] allows no names.
  • A request for a stream name outside the grant gets 403.

How grants combine:

SetupEffective grant
authorize onlyThe grant that authorize returns
tokens onlyThe verified token's grant. A request without a token is denied.
BothThe overlap of both: shared permissions and shared names. A token never adds access.

With both set, a request without a token uses the authorize grant alone.

What the browser receives

The handler passes the allowed stream names to core runs.subscribe(runId, { streams }). With streams=none, it passes streams: false. Core never reads names outside that list, and they never enter the cursor. Payload, output, and metadata are stored on the run record, so the handler reads them with it. It then removes the fields the grant does not allow. Forbidden values are never sent.

A snapshot can contain only these fields:

  • Always: id, environment, taskId, status, counters.attempts, eventSequence, version, createdAt, updatedAt, startedAt, and finishedAt.
  • With Meta: meta.
  • With Output: output, and failure with only name, code, message, and retryable.

The handler never sends failure stacks or failure metadata. It also never sends payloads, wait tokens, application keys, tags, queues, policies, source identity, leases, trace carriers, or hook state.

runRealtimeSnapshotSchema owns this list. The browser's RunSubscriptionEvent snapshot uses this restricted type. Core subscriptions still return the full run record. When the grant hides a status or metadata event, the handler sends a cursor-only checkpoint instead, so a reconnect still moves forward.

Scoped tokens

Token options

RunlaneRealtimeTokenOptions is { audience, keyId, key, verifyKeys? }.

FieldRules
audienceNon-empty string. Tokens for another audience are rejected.
keyId1 to 128 characters. Sent in the token header as kid.
keyWeb Crypto HMAC-SHA256 secret key, at least 256 bits, with sign and verify usage
verifyKeysOptional record of older keys by ID. Each needs verify usage. It cannot repeat the active keyId.

Invalid options throw before the first request. At request time, an unknown key ID, a bad signature, or an expired token returns a safe 403.

Keep every key on the server. Keep old keys in verifyKeys until the tokens they signed expire.

createToken

realtime.createToken({ runId, grant?, expiresIn? }) returns a signed token for the runtime's environment.

OptionRules
runIdRequired. A plain string is fine. It is validated and branded.
grantDefaults to every RunReadPermission, with no stream-name limit
expiresInDefaults to contractDefaults.realtime.tokenTTL. Whole seconds from 1s up to contractDefaults.realtime.maxTokenTTL.

createToken takes no Request. It does not call authorize, and it does not check that the run exists. Your app must check the user's access before it mints a token, including in server actions and token refresh routes. When authorize is set, it still limits every connection that uses the token.

ProblemError
Invalid run ID or grantvalidation_failed
tokens not configuredconfiguration_invalid
Invalid expiresInconfiguration_invalid

The package has no token endpoint and no default access policy. See use tokens for routes you can copy.

Token format

  • Tokens are compact JWS with canonical, unpadded base64url segments. The format still accepts tokens issued by earlier Runlane versions.
  • The header is exactly { alg: 'HS256', typ: 'JWT', kid }.
  • The claims are a VerifiedRunToken: { environment, runId, grant, audience, issuedAt, expiresAt, version: 1 }. Times are whole Unix seconds.
  • issuedAt can be up to contractDefaults.realtime.issuedAtLeeway ahead of the server clock. Expiry has no leeway.
  • Verification rejects unknown fields, versions, algorithms, and key IDs. It also rejects bad signatures, issue times beyond the leeway, expired tokens, lifetimes that are too long, and mismatched scopes.
  • The server reads tokens only from the Authorization: Bearer header.
  • A request with an invalid token gets 403. The handler does not fall back to authorize with cookies.

Browser client

createRunlaneClient({ baseUrl, refreshAccessToken?, fetch?, telemetry?, onTelemetryError? }) returns a RunlaneClient. You own its lifetime. One client can serve readers for many runs. Each reader keeps its own token.

baseUrl is the absolute http or https URL of the handler's mount. It cannot contain a user name, password, query, or fragment.

CallReturns
client.subscribe<TTask = unknown>(runId, options?)AsyncGenerator<RunSubscriptionEvent<TTask>, void>
client.readStream<TTask = unknown, TName = RunStreamName<TTask>>(runId, name, options?)AsyncGenerator<RunStreamRecord<RunStreamPart<TTask, TName>>, void>

Reader options

RunlaneClientReadOptions is shared by both readers:

OptionMeaning
accessTokenToken for the first connection
afterResume cursor
signalAbortSignal. Aborting ends the iterator without an error. It does not cancel the run.
onConnectionChange(change: RealtimeConnectionChange) => void. See connection state.

subscribe() takes RunlaneClientSubscribeOptions: the options above, plus streams?: false. Pass false to leave out stream records, for a connection that only needs status, metadata, and output. Omit it to get every stream the grant allows. readStream() does not take streams. An invalid streams value fails with validation_failed on the first next().

RunSubscribeOptions belongs to core and contracts. The client does not export it. The browser can only leave streams out; the grant chooses which names it may read.

Reader behavior:

  • Wire timestamps are ISO strings. The client turns them into Date objects.
  • Saved stream records arrive before the terminal status.
  • A terminal status, or the server's end event, ends the reader normally.
  • A failed task is data, not a client error.
  • readStream() both catches up and follows. Do not pass it a subscribe() cursor.

refreshAccessToken

refreshAccessToken({ runId, signal }) returns a token string, or a promise of one. Its argument type is RunTokenRequest, exported from @runlane/realtime/client: { readonly runId: RunId; readonly signal: AbortSignal }. Pass signal to your token request.

Token rule

  1. The first connection uses the reader's accessToken. If there is none and a refresher is set, the client calls the refresher first. With neither, the client sends no Authorization header, so same-origin cookies can authorize the request.
  2. Network drops, normal connection rotation, retryable SSE errors, 429, and retryable 5xx responses reconnect with the current token. They do not call the refresher.
  3. A 403 with code access_denied calls the refresher once, then reconnects with the new token. A second 403 in a row, or a 403 with no refresher, ends the reader with access_denied. A successful connection resets this allowance.
  4. If the refresher throws a plain error, the client treats it as a retryable disconnected error that keeps the cause. It uses the normal backoff and failure budget. A thrown RunlaneError with retryable: true does the same. Any other RunlaneError ends the reader at once.
  5. Aborting stops waiting for a refresh. The client ignores a late result and observes a late rejection. It never opens a connection with a late token.

Input checks

ProblemWhenError
Unknown client option, or a refreshAccessToken or fetch that is not a functioncreateRunlaneClient()configuration_invalid
Invalid baseUrlcreateRunlaneClient()configuration_invalid, with the validation error as cause
Invalid run ID or stream nameFirst next()validation_failed, with the validation error as cause
Invalid after cursorFirst next()run_cursor_invalid, with the validation error as cause

Reader input is checked on the first next(). That happens before any token request, network call, or connection notification.

Reconnects

The client uses Fetch streaming, because the browser's EventSource cannot send a bearer header. It rejects redirects.

  • Disconnects, 429, and retryable 5xx responses reconnect after a growing delay with random jitter. reconnect.backoff uses the existing retry backoff shape, including fixed and exponential backoff. Backoff durations and every permitted retry delay must fit the Node timer platform limit of 2,147,483,647 ms. Unlimited exponential retries require maxDelay. The default is exponential, from 250ms up to 10s, owned by contractDefaults.realtime.reconnect.
  • Each reconnect resumes from the last delivered cursor. The server checks access again.
  • Token route failures also count as reconnect failures.
  • Retries continue until caller abort by default (reconnect.maxRetries: 'unlimited'). Set a non-negative integer to allow that many retries after the initial request; zero disables retries. On reaching a finite limit, the reader fails with a non-retryable disconnected error. Its meta.cursor holds the last delivered cursor. Its cause is the last retryable failure, including nested causes such as a token callback error. A plain end of the response body adds no cause.
  • Cursor progress, or a connection that stays open for one heartbeat interval, resets the failure count.

These do not retry: 400 responses, invalid cursors, missing or pruned runs, and malformed wire data. A 403 follows the token rule.

Connection state

RealtimeConnectionChange and its enums live in @runlane/contracts/realtime. Notifications stay in the client and are never sent over the wire. Both readers accept the same callback.

RealtimeConnectionStateWhen and fields
ConnectingBefore each connection attempt
OpenAfter a streaming response passes header checks
Reconnectingattempt counts tries in a row, starting at 1. It resets when a connection opens. delayMs is the jittered wait before the next try, in milliseconds.
Closedreason is RealtimeConnectionCloseReason.Completed, Aborted, or Failed. Failed also has error, a RunlaneError that keeps an unexpected failure as its cause.
  • Each change fires once, in order, and never after the reader ends.
  • A run that ends in failure still closes with Completed, because its result was delivered.
  • If the callback throws, it gets no more notifications and the reader ends. A thrown RunlaneError is kept. Any other value becomes internal_error with the value as cause. This holds even during a retryable failure; the client does not retry it.

Errors

Realtime and React failures all use RunlaneError and ErrorCode. Both @runlane/realtime and @runlane/realtime/client export them. instanceof RunlaneError works even when a bundle holds two copies of the contracts package.

CodeHTTPMeaning
access_denied403Denied by authorize, a token check, or a stream-name limit
validation_failed400Bad request input or grant. Also used when the source throws ConfigurationInvalid or ValidationFailed.
run_cursor_invalid400The cursor does not match this reader, or is malformed
run_not_found404The authorized run is missing or pruned
internal_error500Unexpected failure. The response is safe; the original stays in cause on the server.
event_too_large—One event is over the size limit. Sent as an SSE error. It does not retry.
wire_invalid—The client received malformed data
disconnected—The connection was lost. The server sends a retryable one when it shuts down. The client throws a final one only when a configured finite retry limit is reached.
configuration_invalid—Invalid handler, client, or hook options. Thrown in your code, never sent over the wire.

Before response headers are sent, an error is JSON: { error: { code, message, retryable, cursor? } }. After headers, the same safe error arrives as an SSE error event, and the connection closes.

On the client, a RunlaneError has code, retryable, and an optional checkpoint in meta.cursor. Wire decoding requires message and retryable, and accepts only codes the handler can send. The client maps the wire cursor to meta.cursor.

To throw one yourself, for example from refreshAccessToken:

import { ErrorCode, RunlaneError } from '@runlane/realtime/client'

throw new RunlaneError({
  code: ErrorCode.AccessDenied,
  message: 'Run access denied.',
})

The options type, RunlaneErrorOptions, belongs to @runlane/contracts. It accepts { code, message?, retryable?, meta?, cause? }. message defaults to code, and retryable defaults to false. Set retryable: true yourself for temporary failures. Use cause to keep the original internal error. Never show cause to users. These defaults do not apply to wire decoding.

This package never logs tokens or application bodies.

Frontend type helpers

RunTypes, RunOutput, RunMeta, RunStreams, RunStreamName, and RunStreamPart are types only. Import them from @runlane/contracts/realtime, @runlane/realtime/client, or @runlane/react. They add no runtime code.

import type { RunOutput, RunStreamPart, RunTypes } from '@runlane/realtime/client'

import type { writeAnswer } from './tasks/write-answer'

type Output = RunOutput<typeof writeAnswer>
type AnswerPart = RunStreamPart<typeof writeAnswer, 'answer'>

type Answer = RunTypes<{
  output: { parts: number }
  meta: { progress: number }
  streams: { answer: string; tokens: number }
}>
type Part = RunStreamPart<Answer> // string | number
HelperResult
RunOutput<TTask>The output schema's input type (the stored handler return), or the declared output. Falls back to JsonValue | undefined.
RunMeta<TTask>The declared metadata type, or JsonObject for a core task
RunStreams<TTask>A map from each declared name to its parsed part type
RunStreamName<TTask>A union of the declared names
RunStreamPart<TTask, TName>The parsed part type for that name. Without TName, a union across all names. Undeclared names are type errors.

With no type argument, output is JsonValue | undefined, metadata is JsonObject, streams are Record<string, JsonValue>, names are string, and parts are JsonValue.

How the readers use them:

  • subscribe<TTask> types snapshot and status output as RunOutput<TTask>, and snapshot metadata as RunMeta<TTask>. Both stay optional, because a grant can leave them out.
  • readStream<TTask, TName> types each chunk's value as RunStreamPart<TTask, TName>. It also limits name to declared names.
  • With only TTask, the name type defaults to the union of names. With several part types, pass the name as the second type argument to get an exact type.

Rules:

  • Output uses the schema's input type. Core validates the handler's return value, but stores and sends it unchanged. If an output schema turns a string into an object, the browser still gets the string.
  • Parts use the schema's output type, because writers store parsed parts.
  • No browser validation. These types do not check values. The server validates output and parts when they are written.
  • RunTypes describes the JSON the server sends, in optional output, meta, and streams keys. Interfaces and type aliases both work, with no index signature. It does not check that the types are valid JSON. Leaving out streams means the task has no stream names.

To get these types in another repo, see frontend types.

Wire format and limits

Responses use text/event-stream and Cache-Control: no-store. They send heartbeat comments and id: <cursor> lines. This follows the HTML server-sent events standard, with the Fetch and Streams standards. Tokens use Web Crypto HMAC.

SSE eventData
snapshot, status, meta, streamOn the events route, the subscription event with its cursor
streamOn a stream route, { cursor?, record }
checkpoint, end{}
error{ code, message, retryable, cursor? }

Stream pages

  • A stream route reads contractDefaults.pagination.defaultLimit records per page. Only the last record of a page carries cursor and the SSE id. Earlier records leave the last checkpoint unchanged.
  • After a disconnect, at most one page can be sent again. Within one reader, the client skips record IDs it already delivered, so each record reaches your code once. It only remembers records since the last checkpoint.
  • A new reader started from an older cursor can repeat records after that cursor.

Connection lifetime

  • A connection ends at its token's expiry or after contractDefaults.realtime.connectionDuration, whichever comes first. The client reconnects.
  • On runtime shutdown, the handler sends a retryable error with the last delivered cursor. The client reconnects and can resume on another server.

Size limits

  • contractDefaults.realtime.maxEventBytes is storage.maxRecordBytes plus room for the cursor and SSE envelope. maxBufferedBytes is at least that large.
  • Limits count real UTF-8 bytes after JSON escaping.
  • Every run output, metadata value, and stream part that storage accepts fits in one event. One event over the limit fails with non-retryable event_too_large. Reconnecting cannot fix it.
  • One network read can hold several events. The client limits each event on its own, including comments, IDs, and unknown fields. It rejects invalid UTF-8.
  • An SSE id carries over to later events that have none. An empty id clears it. A parsed id does not move the resume cursor until your code receives that event's record.

Backpressure

The server reads only as fast as the client consumes. A paused reader pauses the source. A stream route keeps one page in memory. It waits for run hints only while idle, and otherwise polls every contractDefaults.streams.pollInterval. It sends checkpoints only when the cursor it checked has changed.

Read all shared limits from contractDefaults.realtime, or from realtimeDefaults in browser code. See defaults for the values.

Proxies and CORS

  • Turn off proxy caching. Allow streaming and request cancellation. Keep idle timeouts longer than contractDefaults.realtime.heartbeatInterval.
  • The handler sends X-Accel-Buffering: no, which nginx follows. If a proxy or CDN ignores or strips it, turn off buffering for the route. In nginx, add proxy_buffering off; to that location.
  • The handler adds no CORS headers, and never a wildcard. Your app owns CORS, including OPTIONS preflight responses and headers on error responses. Allow only your origin, the GET method, and the Authorization and Last-Event-ID headers. See allow another origin for a working adapter.
  • The browser hides CORS failures behind a network error. onConnectionChange then reports Reconnecting with a growing attempt. A redirecting baseUrl also looks like a network failure, because the client rejects redirects.
  • Use HTTPS in production.

Telemetry

Pass telemetry to the handler or the client to record:

  • read and subscribe spans;
  • connection duration and reconnects;
  • authorization denials and authorize exceptions;
  • token rejections.

Access logs hold only the operation and a short, fixed reason. Token rejection reasons are: malformed data, header, unknown key, invalid key, signature, claims, audience, future issue time, expiry, and lifetime. They never include tokens, user values, run IDs, cursors, or stream names. See the signal list.

On this page