Skip to Content
Runlane
Realtime

Set up realtime

Mount the realtime handler and show a live run in a Next.js app.

In this guide, you add a page that starts a task and shows it live. The page shows the run's status, a progress count, the answer as the task writes it, and the final output.

The example uses Next.js and session cookies. The handler works the same way in Hono and Node.js.

You need:

  • An app that already uses Runlane. See add Runlane to your app.
  • A server that can stream HTTP responses.
  • A worker that runs tasks. In development, runlane dev owns the runs in memory and serves app and worker processes over its loopback bridge. Without dev, the first trigger fails. Use createTestLane() for in-process tests.

1. Install the packages

npm install @runlane/realtime @runlane/react cookie

The cookie package parses the session cookie in step 3. The hooks need React 19.

2. Report progress from the task

This task writes ten parts of an answer, half a second apart. It also saves its progress in metadata.

src/tasks/write-answer.ts
import { setTimeout } from 'node:timers/promises'

import { task } from '@runlane/core'
import * as z from 'zod'

export const writeAnswer = task({
  id: 'answer.write',
  schema: z.object({ question: z.string() }),
  output: z.object({ parts: z.literal(10) }),
  streams: { answer: z.string() },
  async run({ question }, context) {
    for (let i = 1; i <= 10; i++) {
      await setTimeout(500, undefined, { signal: context.signal })
      await context.updateMeta({ progress: i, total: 10 })
      await context.stream('answer').append(`Answer to: ${question}. Part ${i} of 10. `)
    }
    return { parts: 10 }
  },
})
  • streams: { answer: z.string() } declares a stream named answer. Each part must be a string.
  • context.updateMeta() saves small JSON values on the run. The page reads them as progress.
  • context.stream('answer').append() saves one part. The page can read it right away.
  • The returned object is the final output. It is separate from the streamed parts.

Register the task in your runtime as usual.

3. Create the realtime handler

The handler decides who may read each run. This one lets a browser read a run only if the run has that browser's session tag.

src/realtime.ts
import { createRunlaneRealtime, RunReadPermission, type RunlaneRealtimeAuthorize } from '@runlane/realtime'
import { parseCookie } from 'cookie'

import { runlane } from './runlane'

const authorize: RunlaneRealtimeAuthorize = async ({ request, runId }) => {
  const session = parseCookie(request.headers.get('cookie') ?? '').session
  if (!session) return undefined

  const run = await runlane.runs.get(runId)
  if (!run?.tags?.includes(`session:${session}`)) return undefined

  return {
    permissions: [
      RunReadPermission.Status,
      RunReadPermission.Meta,
      RunReadPermission.Output,
      RunReadPermission.Streams,
    ],
    streams: ['answer'],
  }
}

export const realtime = createRunlaneRealtime({ runlane, authorize })

authorize runs on every connection. Return a grant to allow access, or undefined to deny it. A grant lists what the reader may see. This one allows status, metadata, output, and the answer stream. See authorize readers for every option, including tokens.

4. Mount the handler

Mount realtime.handle under one path prefix. This guide uses /api/progress. The client adds /runs/:id/events or /runs/:id/streams/:name to that prefix, and the handler reads the end of the path. You do not need to rewrite URLs.

src/app/api/progress/[...path]/route.ts
import { realtime } from '@/realtime'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const GET = realtime.handle

Whatever your framework, keep these four things intact:

  • the Authorization and Last-Event-ID request headers;
  • the request's abort signal, so a closed tab stops the read;
  • the streamed response body, without buffering;
  • GET as the method. Other methods get 405.

5. Tag each run when you start it

Start the run on the server. Add a tag that ties it to the current session. The handler checks this tag in step 3.

src/app/actions.ts
'use server'

import { randomUUID } from 'node:crypto'
import { cookies } from 'next/headers'

import { runlane } from '@/runlane'
import { writeAnswer } from '@/tasks/write-answer'

export async function startAnswer() {
  const cookieStore = await cookies()
  let session = cookieStore.get('session')?.value

  if (!session) {
    session = randomUUID()
    // Also set Secure when you deploy behind HTTPS.
    cookieStore.set('session', session, { httpOnly: true, sameSite: 'lax', path: '/' })
  }

  const { run } = await runlane.trigger(writeAnswer, { question: 'What is Runlane?' }, { tags: [`session:${session}`] })

  return { runId: run.id }
}

This demo creates an anonymous session. In a real app, use your own signed-in user, such as user:${userId}. Never trust a user ID that the browser sends.

6. Show the run in React

Wrap the page in RunlaneProvider and point baseUrl at the mount path from step 4. Then use the two hooks.

src/app/page.tsx
'use client'

import { useState } from 'react'

import { RunlaneProvider } from '@runlane/react'

import { startAnswer } from './actions'
import { RunProgress } from './run-progress'

export default function Home() {
  const [runId, setRunId] = useState<string>()

  async function start() {
    const started = await startAnswer()
    setRunId(started.runId)
  }

  return (
    <RunlaneProvider baseUrl="/api/progress">
      <button type="button" onClick={() => void start()}>
        Start
      </button>
      {runId && <RunProgress runId={runId} />}
    </RunlaneProvider>
  )
}
src/app/run-progress.tsx
'use client'

import { useRun, useRunStream } from '@runlane/react'

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

export function RunProgress({ runId }: { runId: string }) {
  const { run, error } = useRun<typeof writeAnswer>(runId)
  const answer = useRunStream<typeof writeAnswer>(runId, 'answer')

  if (error || answer.error) return <p role="alert">Run progress is unavailable.</p>

  return (
    <section>
      <p>Status: {run?.status ?? 'loading'}</p>
      <p>Progress: {JSON.stringify(run?.meta?.progress ?? 0)} of 10</p>
      <pre>{answer.parts.join('')}</pre>
      <p>Final output: {JSON.stringify(run?.output)}</p>
    </section>
  )
}
  • import type brings in the task's types only. No backend code reaches the browser.
  • useRun returns the run's status, metadata, and output.
  • useRunStream returns the parts of the answer stream. Join them to show the text.
  • The browser sends the session cookie because the page and the API share an origin. No token is needed.

7. Try it

Start the worker in one terminal:

npm exec -- runlane dev

Start your app in a second terminal:

npm run dev

Open the page and click Start. Within a few seconds you should see:

  1. The status change to running.
  2. The progress count go up, and the answer grow, every half second.
  3. The status change to succeeded, and the final output show {"parts":10}.

If triggering fails with storage_unavailable, start runlane dev for the config path in the error and retry. No app restart is needed. If an accepted run stays queued, check the worker's task catalog, queue filter, and environment. See troubleshooting for other problems.

Before you deploy

  • Use a durable lane. The local lane keeps runs only in dev's memory. See choose a lane.
  • Turn off proxy buffering for the realtime route, or events arrive in bursts.
  • Set idle timeouts on proxies and load balancers above contractDefaults.realtime.heartbeatInterval. The handler sends a small heartbeat at that interval.
  • Use HTTPS and set Secure on your session cookie.
  • Test a reconnect. Start a run, cut the network, then reconnect. Text should continue without repeats.
  • Test a denial. Remove a user's access. Their next connection should get 403.

See troubleshooting for proxy settings.

Next steps

On this page