This example showcases the use of httpSubscriptionLink to facilitate useSubscription via Server-sent Events.
Try demo http://sse.trpc.io/
- 🧙♂️ E2E type safety with tRPC
- ⚡ Full-stack React with TanStack Start
- ⚡ Server-Sent-Events / Subscription support
- ⚡ Database with Drizzle
- 🔐 Authorization using Auth.js
This project includes 2 examples of the subscription pattern:
- Simple example of
whoIsTyping - A slightly more involved example of
livePosts
Both subscriptions cover every channel, so switching channels doesn't resubscribe. New posts are added to the channel's cached posts; a channel that isn't loaded yet gets them when it loads. Typing names are picked out per channel.
- The channel page subscribes to both (with
useSubscription) in/src/routes/channels/$channelId.tsx;useLivePostsin/src/routes/channels/-components/hooks.tsadds new posts to the query cache - The
EventEmitter&whoIsTypingsubscription route can be found in/src/server/routers/channel.ts - The more complex
postsubscription route can be found in/src/server/routers/post.ts
Route loaders start the queries a page needs with loadHandles and prefetch entries from @trpc/tanstack-react-query/unstable-handles, and return the handles. Components read them with useSuspenseQuery(fromHandle(trpc, handle)). During SSR, procedures are called in-process with localLink; the browser talks to /api/trpc over HTTP.
git clone git@github.com:trpc/examples-tanstack-start-sse-chat.git
pnpm i
cp .env.example .env
pnpm dev