Loading...
Loading...
Use when streaming durable workflow updates to a UI in real time — live order status pages that animate as steps complete, AI agent token streaming from a function to the browser, log tailing for long-running jobs, or human-in-the-loop approval flows that publish a prompt and wait for a user reply. Covers Inngest v4 native realtime: defining typed channels, publishing from inside step.run, minting subscription tokens via server actions, and consuming the stream from React/Next.js client components.
npx skill4agent add inngest/inngest-skills inngest-realtimeThese skills are focused on TypeScript. For Python or Go, refer to the Inngest documentation for language-specific guidance. Core concepts apply across all languages.
⚠ CRITICAL: v3 vs v4 package selectionRealtime in Inngest v4 lives at the SDK subpath. The standaloneinngest/realtimenpm package is a v3-era package and is NOT compatible with@inngest/realtime. If your project is on v4 (the npm default), do not installinngest@4.x. Use the imports below.@inngest/realtimeSymptoms of using the wrong package on v4:on everyTypeError: Cls is not a constructor, 401 on subscription tokens, type incompatibility onPUT /api/inngest. Verify yournew Inngest({ middleware: [...] })showspackage.jsonbefore reading further."inngest": "^4.x"
npm install inngestinngest-setupINNGEST_DEV=1.env.localnpx inngest-cli@latest devzod| Problem shape | Pattern |
|---|---|
| Order status page animates as durable workflow steps complete | Per-run channel, publish per step, client subscribes |
| AI agent streams tokens to a chat UI | Per-conversation channel, publish chunks, stream to browser |
| Log tail for a long-running job | Single channel, log topic, append to UI |
| Human-in-the-loop approval | Channel + waitForEvent, publish prompt, wait for response |
| Admin dashboard with live order list | Global admin channel, fan-out from each function |
step.realtime.publishinngest.realtime.publishstep.runuseRealtimesubscribe()// src/inngest/channels.ts
import { channel } from 'inngest/realtime';
import { z } from 'zod';
// Per-run channel: each fulfill-order run publishes step updates to its own channel.
export const orderChannel = channel({
name: (orderId: string) => `order:${orderId}`,
topics: {
step: {
schema: z.object({
name: z.string(),
status: z.enum(['running', 'complete', 'failed']),
output: z.record(z.string(), z.unknown()).optional(),
ts: z.number(),
}),
},
},
});
// Global admin channel: fan-out for cross-cutting visibility.
export const adminChannel = channel({
name: 'admin',
topics: {
order: {
schema: z.object({
orderId: z.string(),
step: z.string(),
status: z.enum(['running', 'complete', 'failed']),
ts: z.number(),
}),
},
},
});name: 'admin'adminChannel.ordername: (id) => 'channel:${id}'orderChannel(id).steppublish| Where you are | Use this | Why |
|---|---|---|
Outside a step (top-level handler code, between | | Wraps the publish in its own step so it's durable, deduplicated by |
Inside a step (inside the callback passed to | | You're already inside a memoized step. |
| Outside a function (one-off route, script, etc.) | | Allowed, but not retry-safe — your client receiver must handle duplicates. |
publishstep.realtime.publishstep.runpublishinngest.realtime.publish// src/inngest/functions/fulfill-order.ts
import { inngest } from '../client';
import { orderChannel, adminChannel } from '../channels';
export const fulfillOrder = inngest.createFunction(
{
id: 'fulfill-order',
retries: 3,
triggers: [{ event: 'store/order.placed' }],
},
async ({ event, step }) => {
const { orderId, customerEmail, lineItems } = event.data;
// Outside any step.run — use step.realtime.publish for a durable wrapper.
const emit = async (
name: string,
status: 'running' | 'complete' | 'failed',
output?: Record<string, unknown>,
) => {
const ts = Date.now();
await step.realtime.publish(
`emit-order-${name}-${status}`,
orderChannel(orderId).step,
{ name, status, output, ts },
);
await step.realtime.publish(
`emit-admin-${name}-${status}`,
adminChannel.order,
{ orderId, step: name, status, ts },
);
};
await emit('capture-payment', 'running');
// Inside step.run — use inngest.realtime.publish (already in a memoized step).
const payment = await step.run('capture-payment', async () => {
const intent = await stripe.paymentIntents.create({ /* ... */ });
// Stream a partial update mid-step. No step-in-step wrapping needed.
await inngest.realtime.publish(orderChannel(orderId).step, {
name: 'capture-payment',
status: 'running',
output: { stage: 'intent-created', intentId: intent.id },
ts: Date.now(),
});
return await stripe.paymentIntents.confirm(intent.id);
});
await emit('capture-payment', 'complete', payment);
await emit('reserve-inventory', 'running');
const inventory = await step.run('reserve-inventory', async () => {
// ...
});
await emit('reserve-inventory', 'complete', inventory);
// ...
},
);@inngest/realtimerealtimeMiddleware()publishstep.realtimeinngest.realtime// src/app/orders/[orderId]/actions.ts
'use server';
import { getClientSubscriptionToken } from 'inngest/react';
import { inngest } from '@/inngest/client';
import { orderChannel } from '@/inngest/channels';
export async function fetchOrderSubscriptionToken(orderId: string) {
// ⚠ AUTHORIZATION GATE: verify the current user owns this orderId
// before minting a token. Channels are addressable by ID, so without
// an ownership check, anyone can subscribe to any order's stream by
// guessing IDs.
//
// const session = await getServerSession();
// if (!session) throw new Error('Unauthenticated');
// const order = await db.order.findUnique({ where: { id: orderId } });
// if (order?.userId !== session.userId) throw new Error('Forbidden');
return getClientSubscriptionToken(inngest, {
channel: orderChannel(orderId),
topics: ['step'],
});
}getClientSubscriptionTokeninngest/reactuseRealtimegetSubscriptionTokensubscribe()useRealtimeuseRealtimeinngest/react// src/components/OrderStatusClient.tsx
'use client';
import { useRealtime } from 'inngest/react';
import { orderChannel } from '@/inngest/channels';
import { fetchOrderSubscriptionToken } from '@/app/orders/[orderId]/actions';
export function OrderStatusClient({ orderId }: { orderId: string }) {
const { messages, connectionStatus, error } = useRealtime({
channel: orderChannel(orderId),
topics: ['step'] as const,
token: () => fetchOrderSubscriptionToken(orderId),
});
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<div>Status: {connectionStatus}</div>
<ul>
{messages.all.map((m, i) => (
<li key={i}>
{(m.data as { name: string }).name}: {(m.data as { status: string }).status}
</li>
))}
</ul>
</div>
);
}| Option | Default | Use it when |
|---|---|---|
| | Delay the subscription until you have an ID (e.g., |
| | Batch updates from a fast stream so React doesn't re-render per message. |
| | Pause the stream when the tab isn't visible (saves bandwidth). |
| | Disconnect when the run completes — turn off to keep the stream open for fan-out channels. |
| unbounded | Cap how many messages are retained in |
messages.byTopicmessages.allmessages.lastmessages.deltauseRealtimesubscribe()// src/app/orders/[orderId]/actions.ts
'use server';
import { getSubscriptionToken } from 'inngest/realtime';
import { inngest } from '@/inngest/client';
import { orderChannel } from '@/inngest/channels';
export async function fetchOrderSubscriptionTokenLowLevel(orderId: string) {
// ⚠ AUTHORIZATION GATE: same as Step 3 — verify ownership before minting.
const token = await getSubscriptionToken(inngest, {
channel: orderChannel(orderId),
topics: ['step'],
});
// ⚠ CRITICAL: strip the ChannelInstance from the response.
// getSubscriptionToken returns { channel: ChannelInstance, ... } where
// ChannelInstance contains zod schema methods (a class with prototypes).
// Next.js refuses to serialize classes across the server-action → client-component
// boundary, so return ONLY primitives.
return {
channel: orderChannel(orderId).name as string,
topics: ['step'] as const,
key: token.key,
apiBaseUrl: token.apiBaseUrl,
};
}// src/components/OrderStatusManual.tsx
'use client';
import * as React from 'react';
import { subscribe } from 'inngest/realtime';
import { fetchOrderSubscriptionTokenLowLevel } from '@/app/orders/[orderId]/actions';
export function OrderStatusManual({ orderId }: { orderId: string }) {
const [messages, setMessages] = React.useState<unknown[]>([]);
React.useEffect(() => {
let cancelled = false;
let sub: { close?: (reason?: string) => void } | undefined;
(async () => {
const token = await fetchOrderSubscriptionTokenLowLevel(orderId);
if (cancelled) return;
sub = await subscribe(
{
channel: token.channel,
topics: [...token.topics],
key: token.key,
apiBaseUrl: token.apiBaseUrl,
},
(message) => {
if (cancelled) return;
setMessages((prev) => [...prev, message.data]);
},
);
})();
return () => {
cancelled = true;
sub?.close?.('unmount');
};
}, [orderId]);
// ... render ...
}// src/app/api/orders/[orderId]/stream/route.ts
import { inngest } from '@/inngest/client';
import { subscribe } from 'inngest/realtime';
import { orderChannel } from '@/inngest/channels';
export async function GET(req: Request, { params }: { params: { orderId: string } }) {
// ⚠ AUTHORIZATION GATE: same rule as the server-action token mint above.
// Authenticate the request and confirm the caller owns params.orderId
// before opening the SSE stream. Skipping this leaks every order's
// step events to anyone with a URL.
const stream = await subscribe({
app: inngest,
channel: orderChannel(params.orderId),
topics: ['step'],
});
return new Response(stream.getEncodedStream(), {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
}fetch().getReader()subscribe()subscribe()step.realtime.publishstep.waitForEventimport crypto from 'crypto';
export const reviewWorkflow = inngest.createFunction(
{ id: 'review-workflow', triggers: [{ event: 'review/start' }] },
async ({ event, step }) => {
const confirmationId = await step.run('gen-id', () => crypto.randomUUID());
// Publish a prompt — the client subscribes and renders an approval UI
await step.realtime.publish(
'publish-prompt',
reviewChannel.message,
{ message: 'Confirm to proceed?', confirmationId },
);
// Wait up to 15 minutes for the user to send the matching event back
const confirmation = await step.waitForEvent('await-confirmation', {
event: 'review/confirmation',
timeout: '15m',
if: `async.data.confirmationId == "${confirmationId}"`,
});
if (!confirmation) {
// user didn't respond — abort or escalate
return { decision: 'timed_out' };
}
// continue workflow...
},
);confirmationId@inngest/realtime@inngest/realtimeinngest/realtimeTypeError: Cls is not a constructorPUT /api/inngestgrep '"inngest"' package.json^4.xinngest/realtimegetSubscriptionToken{ channel: ChannelInstance, ... }getClientSubscriptionTokeninngest/reactINNGEST_DEV=1INNGEST_SIGNING_KEYINNGEST_EVENT_KEY.env.local.env.localvalidate: falsesubscribe()import { channel } from 'inngest/realtime'import { useRealtime, getClientSubscriptionToken } from 'inngest/react'import { getSubscriptionToken, subscribe } from 'inngest/realtime'step.realtime.publish(id, topicRef, data)step.runinngest.realtime.publish(topicRef, data)inngest.realtime.publish(topicRef, data)subscribe(token)subscribe(token, callback)ChannelInstance{ channel: string, topics, key, apiBaseUrl }getClientSubscriptionToken