DEV Community

ArcCosine
ArcCosine

Posted on

3

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
kavinda1995 profile image
Kavinda Jayakody

This totally saved me hours of work and frustration. Thank you. Why Haven't this still fixed? I'm using nextjs 14 and next-pwa 5.6.0

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️