Authorize readers
Decide who can read each run, with session cookies, signed tokens, or both.
Every realtime connection must be allowed by your app. Runlane does not know your users, so you tell it who may read each run.
Choose a mode
You can check a session cookie, check a signed token, or do both.
| Setup | A request is allowed when | Removing access takes effect |
|---|---|---|
authorize only | Your authorize function returns a grant | On the next connection |
tokens only | The request has a valid token for this run | When the token expires |
| Both | A sent token is valid, and authorize returns a grant | On the next connection |
Use this rule:
- Browser and API on the same origin? Use
authorizeonly. There are no tokens to mint or refresh. - Frontend on another origin? Use
tokensonly. Browsers do not send cookies to another origin by default. - Want to hand out a token when a run starts, and still cut off removed users quickly? Use both.
You must set at least one. createRunlaneRealtime() throws configuration_invalid if you set neither.
Grants
A grant says what a reader may see on one run. Both authorize and tokens use grants.
import { RunReadPermission, type RunAccessGrant } from '@runlane/realtime'
const grant: RunAccessGrant = {
permissions: [RunReadPermission.Status, RunReadPermission.Meta, RunReadPermission.Streams],
streams: ['answer'],
}| Permission | Lets the reader see |
|---|---|
Status | The run snapshot and status changes. useRun needs it. |
Meta | Metadata and its updates |
Output | The final output, and a short summary if the run failed |
Streams | Stream parts. Use streams to limit which names. |
- Leave out
streamsto allow every stream name. Usestreams: []to allow none. - The server removes anything you do not grant. It never reaches the browser.
- A reader that asks for a stream it may not read gets
403.
See the run object for which fields each permission unlocks.
Use session cookies
Write one function that checks the session and the run. Runlane calls it on every connection.
import { RunReadPermission, type RunAccessGrant } from '@runlane/realtime'
import { runlane } from './runlane'
/** Returns what this user may read on this run, or undefined to deny. */
export async function getRunGrant(userId: string, runId: string): Promise<RunAccessGrant | undefined> {
const run = await runlane.runs.get(runId)
if (!run?.tags?.includes(`user:${userId}`)) return undefined
return {
permissions: [
RunReadPermission.Status,
RunReadPermission.Meta,
RunReadPermission.Output,
RunReadPermission.Streams,
],
streams: ['answer'],
}
}import { createRunlaneRealtime } from '@runlane/realtime'
import { getSession } from './auth'
import { getRunGrant } from './run-access'
import { runlane } from './runlane'
export const realtime = createRunlaneRealtime({
runlane,
async authorize({ request, runId }) {
const session = await getSession(request)
if (!session) return undefined
return getRunGrant(session.userId, runId)
},
})getSession stands for your app's own session check. It reads the cookie from the request and returns the signed-in user.
Follow these rules:
- Get the user from the session. Never trust a user ID that the browser sends.
- Tag runs on the server. Add a tag such as
user:${userId}when you trigger the run, then check it inauthorize. The browser cannot change tags. - Deny by default. Return
undefinedfor unknown runs and missing sessions. - Expect errors to be hidden. If
authorizethrows, the reader gets a500with a safe message.
The client needs no token options. Same-origin requests send the cookie on their own:
<RunlaneProvider baseUrl="/api/progress">{children}</RunlaneProvider>Use tokens
A token is a short signed string. It says "this reader may see this run until this time." Your server signs it with a secret key. The browser sends it in the Authorization header.
1. Create a signing key
Generate a 256-bit secret once and store it in your secret manager:
openssl rand -base64 32Load it on the server as a Web Crypto key:
const secret = process.env.REALTIME_SIGNING_KEY
if (!secret) throw new Error('Set REALTIME_SIGNING_KEY.')
export const signingKey = await crypto.subtle.importKey(
'raw',
Buffer.from(secret, 'base64'),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify'],
)The key must be HMAC-SHA256 with at least 256 bits. It needs both sign and verify. Keep it on the server. Never send it to a browser.
2. Turn on tokens
import { createRunlaneRealtime } from '@runlane/realtime'
import { runlane } from './runlane'
import { signingKey } from './signing-key'
export const realtime = createRunlaneRealtime({
runlane,
tokens: { audience: 'web', keyId: 'v1', key: signingKey },
})| Option | Meaning |
|---|---|
audience | A name for the app that uses the tokens, such as 'web'. A token for another audience is rejected. |
keyId | A name for this key, 1 to 128 characters. It lets you rotate keys later. |
key | The signing key from step 1. |
verifyKeys | Optional. Older keys that can still verify tokens, by key ID. |
With tokens only, a request without a token is denied.
3. Mint a token when you start a run
Check the user first. Then trigger the run and return its ID with a token.
import { getSession } from './auth'
import { realtime } from './realtime'
import { runlane } from './runlane'
import { writeAnswer } from './tasks/write-answer'
export async function POST(request: Request): Promise<Response> {
const session = await getSession(request)
if (!session) return new Response(null, { status: 401 })
const { run } = await runlane.trigger(
writeAnswer,
{ question: 'What is Runlane?' },
{ tags: [`user:${session.userId}`] },
)
const accessToken = await realtime.createToken({ runId: run.id })
return Response.json({ runId: run.id, accessToken }, { headers: { 'Cache-Control': 'no-store' } })
}createToken() signs whatever you ask for. It does not check access, and it does not check that the run exists. That is why your route checks the user first.
| Option | Default |
|---|---|
runId | Required. The run this token can read. |
grant | Every permission and every stream. Pass a smaller grant to narrow it. |
expiresIn | contractDefaults.realtime.tokenTTL. Whole seconds, such as '90s', up to contractDefaults.realtime.maxTokenTTL. |
4. Pass the token to the reader
const { run } = useRun<typeof writeAnswer>(runId, { accessToken })
const answer = useRunStream<typeof writeAnswer>(runId, 'answer', { accessToken })The plain client takes the same option: client.subscribe(runId, { accessToken }).
5. Refresh expired tokens
A connection closes when its token expires. Add a route that checks access again and returns a fresh token. It validates the run ID with @runlane/contracts, so install that package too:
import { createRunlaneIdSchema } from '@runlane/contracts/realtime'
import { getSession } from './auth'
import { realtime } from './realtime'
import { getRunGrant } from './run-access'
const runIdSchema = createRunlaneIdSchema<'run'>('Run id')
// Your router passes the :runId path parameter.
export async function POST(request: Request, runId: string): Promise<Response> {
const session = await getSession(request)
if (!session) return new Response(null, { status: 401 })
const parsed = runIdSchema.safeParse(runId)
if (!parsed.success) return new Response(null, { status: 403 })
const grant = await getRunGrant(session.userId, parsed.data)
if (!grant) return new Response(null, { status: 403 })
const accessToken = await realtime.createToken({ runId: parsed.data, grant })
return Response.json({ accessToken }, { headers: { 'Cache-Control': 'no-store' } })
}Then give the provider a refreshAccessToken function that calls it:
'use client'
import type { ReactNode } from 'react'
import { RunlaneProvider } from '@runlane/react'
import { ErrorCode, RunlaneError } from '@runlane/realtime/client'
import * as z from 'zod'
const tokenResponseSchema = z.object({ accessToken: z.string() })
export function ProgressProvider({ children }: { children: ReactNode }) {
return (
<RunlaneProvider
baseUrl="/api/progress"
refreshAccessToken={async ({ runId, signal }) => {
const response = await fetch(`/api/runs/${encodeURIComponent(runId)}/token`, { method: 'POST', signal })
// Stop for good: this user cannot read the run.
if (response.status === 401 || response.status === 403)
throw new RunlaneError({ code: ErrorCode.AccessDenied, message: 'Run access denied.' })
// Try again later: the failure may be temporary.
if (!response.ok) throw new Error('Run token request failed.')
return tokenResponseSchema.parse(await response.json()).accessToken
}}
>
{children}
</RunlaneProvider>
)
}Here is when the client asks for a token:
- The first connection uses
accessToken. If you did not pass one, the client callsrefreshAccessTokenfirst. - A dropped network connection reconnects with the same token.
- A
403callsrefreshAccessTokenonce. A second403in a row stops the reader withaccess_denied. - If
refreshAccessTokenthrows a plainError, the client waits and tries again. If it throws aRunlaneError, the reader stops at once, unless the error hasretryable: true.
See the token rule for the exact behavior.
Use tokens and authorize together
Set both options to check the token and your live policy on every connection:
export const realtime = createRunlaneRealtime({
runlane,
tokens: { audience: 'web', keyId: 'v1', key: signingKey },
async authorize({ request, runId }) {
const session = await getSession(request)
if (!session) return undefined
return getRunGrant(session.userId, runId)
},
})The reader gets only what both allow. A token can never give more than authorize.
- A request with a token must have a valid one. A bad token is denied, and the handler does not fall back to the cookie.
- A request without a token skips the token check.
authorizealone decides, for example from the session cookie.
Rotate signing keys
To replace a key without breaking open readers:
- Create a new key with a new
keyId. - Move the old key into
verifyKeysunder its old ID. - After
contractDefaults.realtime.maxTokenTTLhas passed, remove the old key.
tokens: {
audience: 'web',
keyId: 'v2',
key: newSigningKey,
verifyKeys: { v1: oldSigningKey },
}New tokens use v2. Tokens signed with v1 keep working until they expire. Keys in verifyKeys need only verify usage. Do not repeat the active keyId in verifyKeys.
Allow another origin (CORS)
The handler adds no CORS headers. If your frontend runs on another origin, wrap the handler:
export function withProgressCors(handle: (request: Request) => Promise<Response>, allowedOrigin: string) {
return async (request: Request): Promise<Response> => {
if (request.headers.get('origin') !== allowedOrigin) return new Response(null, { status: 403 })
const cors = new Headers({
'access-control-allow-origin': allowedOrigin,
'access-control-allow-methods': 'GET',
'access-control-allow-headers': 'Authorization, Last-Event-ID',
vary: 'Origin',
})
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors })
const response = await handle(request)
const headers = new Headers(response.headers)
cors.forEach((value, name) => headers.set(name, value))
return new Response(response.body, { status: response.status, headers })
}
}- Use
tokensonly. This adapter does not allow cookies. - Pass your frontend's origin, such as
https://app.example.com, asallowedOrigin. - In Next.js, export the wrapped function as both
GETandOPTIONS. In Hono, useapp.all('/api/progress/*', ...). - On the client, set
baseUrlto the full API URL, such ashttps://api.example.com/api/progress. - If your token route is on another origin too, give it its own CORS headers.
A CORS mistake looks like a network error in the browser. See troubleshooting.