shadowwalker / next-pwa

Zero config PWA plugin for Next.js, with workbox 🧰
MIT License
3.75k stars 311 forks source link

Note on usage with TurboRepo #449

Open bruceharrison1984 opened 1 year ago

bruceharrison1984 commented 1 year ago

I just wanted to let others know, there is some weirdness using this library with Turborepo. This is not anything wrong with next-pwa, but with how Turborepo manages outputs.

Since the files next-pwa creates are placed in the public directory, not the .next, you need to make sure to include them in your turbo.json configuration. If you don't, when you deploy to something like Vercel, your TurboRepo build will be replayed, but the service-worker files will not be added to the public directory, despite seeing them generated in the playback logs. I ran around with Vercel for hours before I realized that the reason my sw.js file was missing was because it truly wasn't being placed in the domain root.

You can easily test this locally by running a build, and viewing the SW files in public. Now delete those files, and run another build. Turborepo will use the cached build, but the SW files are not put back into public

In order to avoid this behavior, you need to add the SW.js files to your turbo.json config.

{
  "$schema": "https://turbo.build/schema.json",
  "pipeline": {
    "build": {
      "dependsOn": [
        "^build"
      ],
      "outputs": [
        ".next/**",
        "lib",
        "public/*.js"  // <-- add JS files to watched output
      ]
    },
    "dev": {
      "dependsOn": [
        "build"
      ],
      "cache": false
    },
    "lint": {}
  }
}

Alternatively, the first way I got around it was running npm run build -- --force as my Vercel build command. This skips reading the cache, and forces a "real" build to occur again. The places the SW files correctly into public, where Vercel can serve it up. However, altering the turbo.json file is the better solution because it allows you to utilize cached builds.

I posted this to hopefully help someone else who runs into this issue, and possibly for the maintainers of this repo to make a small note in the documentation.