Enable Next.js route handlers to handle WebSocket and other Upgrade requests #58698
Replies: 4 comments 4 replies
-
@AaronFriel I'm having the same issue because Next.JS doesn't allow me to handle Connection upgrade requests the way I want to.
Letting the API handler take over and handle the Upgrade requests will enable developers to customize how they want to deal with custom websocket solutions. Right now this is practically impossible without patching next.js. If anyone stumbles upon this thread and is also building a TRPC integration with websockets and wants to have a websocket server on the same port as your website, here's my really long workaround. Click here to see my really long workaroundThis is how I worked around my niche but complicated issue - I needed next.js server to handle socket upgrade requests for the socket server to use the same port as next.js. 🛑 This will NOT work on vercel, use only if self-hosting using
|
Beta Was this translation helpful? Give feedback.
-
any update on this to make Websocket stable feature on NEXTJS |
Beta Was this translation helpful? Give feedback.
-
I'm looking for a solution to socket.io on app router too |
Beta Was this translation helpful? Give feedback.
-
This should 100% be a feature on NextJS! |
Beta Was this translation helpful? Give feedback.
-
Goals
Non-Goals
Background
Websockets enable low latency, "sticky" communication channels with a backend. These are useful, for example, for rendering a terminal shell (xterm.js), for multiplayer experiences (socket.io), and for interactive chat.
Being able to host a websocket server directly in a route handler would enable these and many more applications.
Proposal
First, remove the
.on('upgrade')
handler in router-server:next.js/packages/next/src/server/lib/router-server.ts
Lines 566 to 606 in 43b075e
This is in fact unnecessary for HMR. Adding an
.on('upgrade')
handler circumvents the HTTP server's ordinary routing and middleware. As I expect the most common use of middleware is security - whether handling session cookies, authentication or authorization - this is an anti-pattern.Instead, add
ws
as a dependency (from a dev dependency), and modify therequestHandlerImpl
like so:This preserves the same behavior for HMR / developer workflows, but it enables GET route handlers to receive upgrade requests.
Second, an
upgrade
response handler method toNextRequest
. This is straightforward for the Node runtime to support, but may require some engineering for the Edge runtime (as seen in other edge runtimes).With this handler providing access to the underlying request and socket, a WebSocket route is straightforward to implement.
Alternatively, an
UPGRADE
route handler could be added to support this use case.Beta Was this translation helpful? Give feedback.
All reactions