Enable PWA with next.js 13 or later using next-pwa (disabled in development environment)

arccosine

ArcCosine

Posted on May 28, 2023

Enable PWA with next.js 13 or later using next-pwa (disabled in development environment)

Maybe next-pwa will support it in time, so you can wait and it will be fine, but this is a patch code for those who really want to support it right now. Version,

  • next ^13.4.2
  • next-pwa ^5.6.0

The file to be modified is next-pwa ^5.6.0. The file to be modified is next.config.js

next.config.js

/** @type {import('next').NextConfig} */
const path = require("path");
const isDev = process.env.NODE_ENV !== "production";
const withPWA = require("next-pwa")({
dest: "public",
disable: isDev,
buildExcludes: ["app-build-manifest.json"],
});
const generateAppDirEntry = (entry) => {
const packagePath = require.resolve("next-pwa");
const packageDirectory = path.dirname(packagePath);
const registerJs = path.join(packageDirectory, "register.js");
return entry().then((entries) => {
// Register SW on App directory, solution: https://github.com/shadowwalker/next-pwa/pull/427
if (entries["main-app"] && !entries["main-app"].includes(registerJs)) {
if (Array.isArray(entries["main-app"])) {
entries["main-app"].unshift(registerJs);
} else if (typeof entries["main-app"] === "string") {
entries["main-app"] = [registerJs, entries["main-app"]];
}
}
return entries;
});
};
const nextConfig = {
experimental: {
appDir: true,
},
reactStrictMode: true,
webpack(config) {
if( !isDev ){
const entry = generateAppDirEntry(config.entry);
config.entry = () => entry;
}
return config;
},
};
module.exports = withPWA(nextConfig);
Enter fullscreen mode Exit fullscreen mode




Referenced Sources

Next v13 app-build-manifest.json - Does not register a service worker that controls page and start_url #424

💖 💪 🙅 🚩
arccosine
ArcCosine

Posted on May 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024