Websockets with TanStack Start
For the past few weeks I’ve been playing around with TanStack Start, a new full-stack React framework by Tanner Linsley, the creator of React Query and other amazing TanStack libraries. The framework uses Vinxi under the hood, which uses Nitro — the same server technology that powers Nuxt and SolidStart. 1
Full-document SSR, Streaming, Server Functions, bundling and more, powered by TanStack Router, Vinxi, and Vite. Ready to deploy to your favorite hosting provider.
Nitro WebSockets
Nitro provides experimental support for WebSockets, powered by h3 and crossws. This feature can be utilized in Vinxi to enable websockets in our TanStack Start projects.
You can read more at nitro.build/guide/websocket.
Setting up the server
Assuming you already have a TanStack Start project set up (or you can use my tanstarter template), let’s get started by setting up a new websocket handler.
- First, let’s enable experimental Nitro websockets in our app config.
- Next, let’s create a new websocket handler in our app.
- Finally, add a new Vinxi router to handle the websocket requests.
Our server is now ready to handle websocket connections at /_ws
. We can test it out by connecting from our client.
Example client
Here’s a minimal example implementation of a websocket client connecting to our server. You probably want to use a library or a more robust implementation in a real-world scenario.
Handling authentication
You can perform authentication checks in the upgrade
hook. This is supported in Vinxi 0.5.0 and later.
Read more about crossws
hooks at crossws.unjs.io/guide/hooks.
I’m currently working on a full example project with websockets, which I’ll share in this post soon once these issues are resolved:
Footnotes
-
SolidStart is a full-stack framework for Solid that also uses Vinxi. This guide should likely work for SolidStart as well, with some adjustments. ↩