Key Concepts
Socket.IO: Use Socket.IO to simplify WebSocket handling between client and server, emitting and listening for named events like
event-from-server.Development approach (Vite plugin):
- Hook into Vite's dev server via a custom plugin with
configureServer. - Instantiate Socket.IO with the Vite HTTP server to serve sockets during
pnpm dev.
- Hook into Vite's dev server via a custom plugin with
Tip
A small Vite plugin keeps the development experience unified — no separate server to run.
Client setup:
- Import the client library (
iofromsocket.io-client) in your Svelte route. - Connect (
const socket = io()) and listen for server events, logging or updating reactive state.
- Import the client library (
Production approach (adapter-node + custom Express server):
- Build SvelteKit (produces
buildwithhandler.js) using@sveltejs/adapter-node. - Create an Express server that mounts SvelteKit's handler as middleware:
app.use(handler). - Create an HTTP server (
createServer(app)), attach Socket.IO to that server, and listen on a port so the same process serves both pages and WebSockets.
- Build SvelteKit (produces
Important
Use
@sveltejs/adapter-nodewhen you need to attach Socket.IO in production. Other adapters may not expose a Node HTTP server to bind sockets.
- Build and start scripts:
- Add a
startscript that runs your custom server (node server/index.js) to launch the production server with WebSockets.
- Add a
Quick Decisions & Warnings
- Do not run a separate WebSocket-only server unless you intentionally want two processes and separate ports.
- Remember to restart the dev server after adding the Vite plugin so the
configureServerhook is applied. - Use reactive blocks in Svelte to emit socket messages when local state changes for real-time updates.
Takeaways
- You can support WebSockets in both development and production with SvelteKit by attaching Socket.IO to the underlying Node HTTP server.
- The pattern keeps routing and page serving handled by SvelteKit while enabling real-time features from the same process.
