LoginSignup
15
1

More than 1 year has passed since last update.

next-pwa が動かないよー ウワァァァン

Last updated at Posted at 2021-12-01

本記事の対象者

  • 最近(2021年11月以降)
  • React + Next + next-pwaライブラリを利用したPWAを作成しようとしていて
  • 本番環境でService Workerの問題でPWAが動作しない現象に悩まされている

という人。

要約

  • 現時点(2021-12-02)のnext-pwaライブラリとそのライブラリが利用するworkboxライブラリにおいて、
  • デフォルト設定ではService Workerが正常動作しません。
  • next.config.js に以下のような除外設定を追加する必要があります。
    buildExcludes: [/middleware-manifest.json$/]  // 追加

現象の再現

1. プロジェクト新規作成

node v16.13.0 環境にて、
create-next-app + progressive-web-appテンプレートを使い、
プロジェクトを新規作成します。

## create-next-app + progressive-web-appテンプレートで 新規プロジェクト my-app を作成
npx create-next-app --example progressive-web-app my-app

ローカルの開発環境でdevサーバを立ち上げ、
ブラウザで http://localhost:3000/ を開くと PWAが正常動作する。

## 開発環境で動作確認
cd my-app
npm run dev

2. Vercelにデプロイ

その後 Githubにpushして、Vercelにプロジェクトを取り込んでデプロイします。
(手順省略)

しかし、デプロイされたページをブラウザで見てみると、PWAとしてアプリケーション保存ができません。
Chromeのデベロッパーツールで見てみると、以下の問題が目に付きます。

  1. ChromeのPWAインストールボタンが表示されない

  2. Installabilityに問題あり
    No matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest.
    サービスワーカー関連の問題みたい。

  3. Consoleエラー
    workbox-*.jsの処理にて、Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"https://.../_next/server/middleware-manifest.json","status":404}]というメッセージ。
    middleware-manifest.json が見つからないっぽい。

err.png

何が問題か?

以下で議論されています。
next-pwaライブラリが利用するworkboxライブラリの間にミスマッチがあるか、またはworkboxの問題により、想定外のファイル(middleware-manifest.json)を読み込もうとしているのではないか、と推測しているようです。

next-pwa not working in Production Envrionment · Issue #295 · shadowwalker/next-pwa

対応

ワークアラウンドとして、next.config.js に buildExcludesオプションの記述を追加します。
直接の問題となっているファイル(middleware-manifest.json)を明示的に除外するオプションに指定しています。

next.config.js
const withPWA = require('next-pwa')
const runtimeCaching = require('next-pwa/cache')

module.exports = withPWA({
  pwa: {
    dest: 'public',
    runtimeCaching,
    buildExcludes: [/middleware-manifest.json$/],  // 追加
  },
})

再度Vercelで確認すると、今度は正常にPWAアプリとしてインストールすることができるようになりました。

ok.png

いずれnext-pwaライブラリ、またはworkboxライブラリで対応されると思われますが、今しばらくはこのワークアラウンド対応でしのぎましょう。

15
1
0

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
15
1