Jan 1, 2025
Real-Time Features in Next.js with WebSockets and Server-Sent Events (SSE)
nextjswebsocketssereal-timeapp-router
Next.js does not provide a built-in WebSocket server, but it works well with standard browser APIs and Route Handlers. This post explains how to add real-time behavior using SSE for HTTP streams and WebSockets via external services.
1Clarifies how Next.js, the runtime, and the transport layer (HTTP, SSE, WebSocket) fit together.
2Shows how to implement an SSE endpoint with App Router Route Handlers using ReadableStream.
3Demonstrates how to consume SSE streams from a client component with EventSource.
4Provides a reusable client-side WebSocket hook and chat example for connecting to an external WebSocket server.
5Gives practical guidelines for choosing between SSE and WebSockets based on data flow and infrastructure constraints.