oRPC is currently pre-stable, please report any issues on our Discord or GitHub 🚧
oRPC
background

Event Iterator

Server-Sent Events (SSE) with out-of-the-box support in oRPC

The event iterator in oRPC provides built-in support for streaming responses using Server-Sent Events (SSE) without any extra configuration. This makes it easy to build real-time, event-driven APIs.

Example Usage

The following example demonstrates how to create a streaming endpoint that continuously sends events to the client:

import {  } from '@orpc/client'
import {  } from '@orpc/client/fetch'
import { , ,  } from '@orpc/server'
import {  } from 'zod'
 
// Define a streaming endpoint using the event iterator
const  = 
  // Validate the input with Zod
  .(.({ : .() }))
  // Use eventIterator to specify the streaming output (optional, but recommended)
  .((.({ : .() })))
  .(async function* ({ ,  }) {
    // The lastEventId (if provided) can be used to resume streaming on reconnects
    while (true) {
      // withEventMeta attaches metadata (e.g., event id, retry interval) to each event
      yield (
        { : 'Hello, world!' },
        { : 'some-id', : 1000 }
      )
      // Wait for 1 second before sending the next event
      await new ( => (, 1000))
    }
  })
 
// Create a router with the streaming endpoint
const  = {  }
 
// Create an ORPC client and configure the SSE behavior
const  = <typeof >(
  new ({
    : 'http://localhost:3000/rpc',
    : 0, // Set to 0 to disable automatic retries on connection failure,
    // Optionally, you can configure:
    // - eventSourceRetryDelay: Delay between retry attempts
    // - eventSourceRetry: Custom retry behavior
  })
)
 
// Invoke the streaming endpoint with an initial prompt and optional lastEventId
const  = await .(
  { : 'Hello' },
  { : 'you also can pass initial last event id here' }
)
 
// Process the incoming stream of events using async iteration
for await (const  of ) {
  .()
}
 
// To close the connection manually, call result.return()

Key Concepts

  • lastEventId:
    This parameter represents the ID of the last event received by the client. When reconnecting, the client can send this ID so that the server can resume streaming from where it left off.

  • withEventMeta:
    This helper function attaches additional metadata (such as id and retry) to an event. This metadata is useful for controlling the behavior of SSE, for example:

    • id: A unique identifier for the event. Last event id is used when reconnecting.
    • retry: The suggested reconnection delay (in milliseconds) if the connection is lost.

On this page