Skip to Content
Runlane
Realtime

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.

SetupA request is allowed whenRemoving access takes effect
authorize onlyYour authorize function returns a grantOn the next connection
tokens onlyThe request has a valid token for this runWhen the token expires
BothA sent token is valid, and authorize returns a grantOn the next connection

Use this rule:

  • Browser and API on the same origin? Use authorize only. There are no tokens to mint or refresh.
  • Frontend on another origin? Use tokens only. 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'],
}
PermissionLets the reader see
StatusThe run snapshot and status changes. useRun needs it.
MetaMetadata and its updates
OutputThe final output, and a short summary if the run failed
StreamsStream parts. Use streams to limit which names.
  • Leave out streams to allow every stream name. Use streams: [] 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.

src/run-access.ts
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'],
  }
}
src/realtime.ts
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 in authorize. The browser cannot change tags.
  • Deny by default. Return undefined for unknown runs and missing sessions.
  • Expect errors to be hidden. If authorize throws, the reader gets a 500 with 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 32

Load it on the server as a Web Crypto key:

src/signing-key.ts
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

src/realtime.ts
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 },
})
OptionMeaning
audienceA name for the app that uses the tokens, such as 'web'. A token for another audience is rejected.
keyIdA name for this key, 1 to 128 characters. It lets you rotate keys later.
keyThe signing key from step 1.
verifyKeysOptional. 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.

src/start-answer-route.ts
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.

OptionDefault
runIdRequired. The run this token can read.
grantEvery permission and every stream. Pass a smaller grant to narrow it.
expiresIncontractDefaults.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:

src/refresh-token-route.ts
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:

src/progress-provider.tsx
'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:

  1. The first connection uses accessToken. If you did not pass one, the client calls refreshAccessToken first.
  2. A dropped network connection reconnects with the same token.
  3. A 403 calls refreshAccessToken once. A second 403 in a row stops the reader with access_denied.
  4. If refreshAccessToken throws a plain Error, the client waits and tries again. If it throws a RunlaneError, the reader stops at once, unless the error has retryable: 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. authorize alone decides, for example from the session cookie.

Rotate signing keys

To replace a key without breaking open readers:

  1. Create a new key with a new keyId.
  2. Move the old key into verifyKeys under its old ID.
  3. After contractDefaults.realtime.maxTokenTTL has 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:

src/progress-cors.ts
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 tokens only. This adapter does not allow cookies.
  • Pass your frontend's origin, such as https://app.example.com, as allowedOrigin.
  • In Next.js, export the wrapped function as both GET and OPTIONS. In Hono, use app.all('/api/progress/*', ...).
  • On the client, set baseUrl to the full API URL, such as https://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.

On this page