How WebSockets Work
A WebSocket connection begins as a standard HTTP request with a special Upgrade header. The server responds with a 101 Switching Protocols response, and the connection upgrades from HTTP to the WebSocket protocol. From this point, both client and server can send frames of data to each other at any time without a new request. The connection stays open until either party closes it. This persistent connection is the fundamental difference from HTTP. In HTTP, every interaction requires a new request: the client opens a connection, sends a request, receives a response, and the connection closes (or is reused briefly). The server can never push data to the client unprompted. With WebSockets, the server can push data to the client the moment it is available, enabling genuinely real-time experiences. The connection is bidirectional: the client can also send data to the server at any time, making WebSockets suitable for interactive applications like collaborative editing, live chat, and interactive AI assistants.
WebSockets vs Server-Sent Events for LLM Streaming
For the specific use case of streaming LLM output to a browser, WebSockets and Server-Sent Events (SSE) are both commonly used, with different trade-offs. Server-Sent Events are a simpler, HTTP-based standard where the server sends a stream of text events over a persistent HTTP connection. The client cannot send data over an SSE connection: it is unidirectional, server to client only. SSE is natively supported in browsers without any JavaScript library, works with existing HTTP caching and proxy infrastructure, and is simpler to implement for purely server-to-client streaming. WebSockets are bidirectional, making them appropriate for interactive AI applications where the user sends messages and receives streaming responses, such as a chat interface. The connection is more efficient for high-frequency bidirectional communication because it avoids HTTP header overhead on each message. For most AI chat interfaces, SSE is sufficient and simpler. For collaborative real-time applications or AI interfaces with complex bidirectional interaction patterns, WebSockets are more appropriate.
Real-Time AI Features That Use WebSockets
Several AI product features are natural implementations for WebSocket connections. Streaming chat interfaces, where the AI response appears word by word as it is generated, use either SSE or WebSockets to push partial output from the server to the client as the LLM generates it. Collaborative AI workspaces where multiple users see each other's edits and AI suggestions in real time require WebSockets for the bidirectional synchronisation. Live AI analysis dashboards that update as new data is processed benefit from WebSocket push notifications rather than polling. Background AI job completion notifications, where a user triggers a long-running AI task and receives a notification when it finishes, can use WebSockets to deliver the result without the user refreshing the page. Multi-turn AI agent conversations where the agent is taking actions and reporting progress in real time need persistent connections to stream the agent's intermediate steps to the user.
Implementing WebSockets in Next.js
Next.js running on Vercel does not natively support long-lived WebSocket connections in its serverless function model because serverless functions terminate after the request completes. For WebSocket support in a Next.js application, the options are: use a third-party WebSocket service (Ably, Pusher, or Supabase Realtime) that handles the persistent connection infrastructure and provides a client SDK for the browser; deploy a separate Node.js WebSocket server alongside the Next.js application on a platform that supports persistent connections (Railway, Fly.io, a VPS); or use Vercel's own real-time offerings with PartyKit or similar integrations. For most AI MVPs, a managed WebSocket service like Ably or Pusher is the most practical choice. The managed service handles connection management, scaling, and geographic distribution, and you pay for usage rather than managing persistent server infrastructure. For SSE-based LLM streaming (the more common case), Next.js streaming responses work natively on Vercel without any additional infrastructure.
WebSocket Security and Authentication
WebSocket connections have security considerations that differ from standard HTTP requests. The initial WebSocket handshake is an HTTP request, so standard HTTP authentication (Bearer tokens in the Authorization header) applies at connection time. Once the connection is upgraded, no further authentication occurs unless you implement it at the application level within the WebSocket protocol. This means that if a user's authentication token expires mid-connection, the server needs to handle this gracefully. For AI products handling sensitive data, WebSocket connections should always use WSS (WebSocket Secure, the WebSocket equivalent of HTTPS) to encrypt the connection. For UK products processing personal data over WebSockets, the data in transit must be encrypted, which WSS provides. If personal data is sent over WebSockets, the DPA with your WebSocket service provider must cover this data processing.
When Not to Use WebSockets
WebSockets are not always the right tool. For straightforward request-response interactions, standard HTTP is simpler and sufficient. For server-to-client notifications that are infrequent, HTTP polling (checking for updates every few seconds) or SSE are simpler to implement and easier to debug. WebSocket connections consume server resources for the duration of the connection. At scale, many simultaneous open WebSocket connections require infrastructure that can handle them: load balancers configured for WebSocket passthrough, sticky sessions, and connection management. For AI products where the primary interaction pattern is asynchronous (user submits a task, comes back later to view the result), WebSockets may be more complex than the use case justifies. A simple polling mechanism or email/push notification on completion is often the right starting point, with WebSocket-based real-time updates added later if users request it.