How It Works
Upstash Realtime is powered by Upstash Redis and provides a clean, 100% type-safe API for publishing and subscribing to events:- Your frontend can subscribe to events
- When you emit an event, it’s instantly delivered to live subscribers on the frontend
- You can also replay events that happened in the past
Setup
1. Install Packages
2. Configure Upstash Realtime
Create a Realtime instance inlib/realtime.ts:
3. Create a Realtime Endpoint
Create an API route atapp/api/realtime/route.ts to handle Realtime connections:
app/api/realtime/route.ts
4. Add the Realtime Provider
Wrap your application in theRealtimeProvider by updating your root layout at app/layout.tsx:
app/layout.tsx
5. Create a Typed Client Hook
Create a typeduseRealtime hook at lib/realtime-client.ts:
lib/realtime-client.ts
Building the Workflow
1. Create the Workflow Endpoint
Create your workflow atapp/api/workflow/route.ts:
app/api/workflow/route.ts
- We use
realtime.channel(workflowRunId)to create a unique channel per workflow run - Emit events after each step completes
- Emit events inside
context.runsteps to ensure that they are emitted only once - Events are emitted to separate event names like
workflow.stepFinishandworkflow.runFinish
2. Create a Trigger Endpoint
Create an endpoint to trigger workflows atapp/api/trigger/route.ts:
app/api/trigger/route.ts
Building the Frontend
1. Create a Custom Hook
Create a React hook to manage the Realtime subscription athooks/useWorkflow.ts:
- Subscribe to multiple events using the
eventsarray:["workflow.stepFinish", "workflow.runFinish"] - The hook manages both triggering the workflow and subscribing to updates
- Type-safe event handling with TypeScript
2. Use the Hook in Your Component
How It All Works Together
- User triggers workflow: The frontend calls
/api/trigger, which returns aworkflowRunId - Frontend subscribes: Using the
workflowRunId, the frontend subscribes to the Realtime channel - Workflow executes: The workflow runs as a background job, emitting events at each step
- Real-time updates: As the workflow emits events, they’re instantly delivered to the frontend via Server-Sent Events
Full Example
For a complete working example with all steps, error handling, and UI components, check out the Upstash Realtime example on GitHub.Next Steps
- Learn about human-in-the-loop workflows with Realtime
- Explore Realtime features
- Check out Workflow configuration options