LoginSignup
10
3

More than 1 year has passed since last update.

Next.js 12で開発中のHMRがうまくいかない場合の対処

Last updated at Posted at 2022-07-30

Next.js 12で開発中のHMRがうまくいかない場合の対処方法です。

TL;DR

以下を参照

環境

  • Next.js 12以上
  • nginxやApacheなどをReverse-Proxyとして、Next.js開発サーバーの前段に配置している場合

解説

Next.js 12では、devモードでのコード編集時のホットリロード (HMR) はWebSocketを介してクライント側に通知されるようになりました。

  • 上記環境のように、ReverseProxyとしてWebサーバーを立てて開発している場合、nginxやApacheの設定がされていないとWebSocketのコネクション確率ができずにHMRがうごかなくなる場合があります。
  • この場合、ブラウザ側のconsoleログに WebSocket connection to 'wss://xxxxxx/_next/webpack-hmr' failed などがでる。

対応方法

Next.js公式のアップグレードガイドを参考に、ブラウザ -> Reverse-Proxy -> Next.js 間のWebSocketのコネクション確立時のやりとりができるように設定してあげればOK

nginxの場合

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";
}

apacheの場合

# (mod_rewriteなどは適宜設定)
 <Location /_next/webpack-hmr>
    RewriteEngine On
    RewriteCond %{QUERY_STRING} transport=websocket [NC]
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule /(.*) ws://localhost:3000/_next/webpack-hmr/$1 [P,L]
    ProxyPass ws://localhost:3000/_next/webpack-hmr retry=0 timeout=30
    ProxyPassReverse ws://localhost:3000/_next/webpack-hmr
 </Location>

以上。Apaecheの場合もっと簡潔な書き方があるかも。

余談。これにぶつかるまで、HMRがserver-sent events を使ってるのに気づいてなかったのでびっくりした。

参考

10
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3