Alex Poloz
Alex Poloz

Reputation: 476

WebSocket connection to 'ws://localhost/_next/webpack-hmr' failed: WebSocket is closed before the connection is established in Next.js with Nginx

I do Web app on NextJS with Socket.IO.

When I run my app, everything is fine. But after 2 minutes errors appear.

NGINX logs:

172.19.0.1 - - [12/Sep/2022:16:27:39 +0000] "POST /api/ HTTP/1.1" 200 147 "http://localhost/en" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"
172.19.0.1 - - [12/Sep/2022:16:27:59 +0000] "GET /_next/webpack-hmr HTTP/1.1" 101 269 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"
...
172.19.0.1 - - [12/Sep/2022:16:29:21 +0000] "GET /_next/webpack-hmr HTTP/1.1" 101 71 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"
172.19.0.1 - - [12/Sep/2022:16:29:26 +0000] "GET /_next/webpack-hmr HTTP/1.1" 499 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15"

101 -- fine. 499 -- errors. But nothing happens, where are the errors coming from?

In console I see this error on each 499:

WebSocket connection to 'ws://localhost/_next/webpack-hmr' failed: WebSocket is closed before the connection is established

And this problem only on Safari (MacOS)!

On Chrome everything is okay.

Upvotes: 7

Views: 8552

Answers (1)

juliomalves
juliomalves

Reputation: 50248

From Next.js 12, HMR (Hot Module Replacement) in development uses a WebSocket connection.

When using Nginx with Next.js you'll have to configure it to pass through the WebSocket request properly.

In some cases when proxying requests to the Next.js dev server, you will need to ensure the upgrade request is handled correctly. For example, in nginx you would need to add the following configuration:

location /_next/webpack-hmr {
    proxy_pass http://localhost:3000/_next/webpack-hmr;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade"; 
} 

Next.js, Upgrade Guide, Next.js' HMR connection now uses a WebSocket

Upvotes: 16

Related Questions