Set Up WebSocket Client
Add real-time WebSocket communication to the current project using the shared WebSocket server on Fly.io.
Steps
- •
Copy all files from
/Users/scottzockoll/projects/workshop/services/websocket/files/into the project root, preserving directory structure:- •
src/lib/ws.ts— WebSocket client helper with auto-reconnect - •
src/app/api/ws-token/route.ts— API route that mints short-lived JWTs (requires user auth)
- •
- •
Add WebSocket env vars to
.env.local(create the file if it doesn't exist):codeNEXT_PUBLIC_WS_URL=wss://scottzockoll-ws.fly.dev WS_API_KEY=<get from workshop secrets.env>
Note:
NEXT_PUBLIC_WS_URLis public (just the server address).WS_API_KEYis server-side only — never expose it to the client. - •
Update or create
services.jsonin the project root. If it exists, add"websocket"to the array. If not, create it with["websocket"]. - •
Tell the user:
- •Connect to a room:
const client = createWSClient('my-room') - •Send events:
client.send('event-name', { data }) - •Listen for events:
client.on('event-name', (data) => { ... }) - •Clean up:
client.close() - •Room names can be namespaced with colons:
chess:lobby,chess:game-123 - •The client auto-reconnects with exponential backoff
- •Auth is automatic — the client fetches a 60-second JWT from
/api/ws-tokenbefore connecting
- •Connect to a room: