Next.js + PWA = ⚡️📱

Let’s convert a create-next-app project into a Progressive Web App (PWA)

1. Setup

Let’s create a boilerplate Next.js project using create-next-app (CNA) by running this command:

npx create-next-app

You can open the project folder in your text editor. All terminal commands after this step is assumed to be executed in the project directory.

2. Install next-pwa

Let’s add the next-pwa package to our project. Run :

npm install next-pwa

Or :

yarn add next-pwa

3. Create next.config.js file

You can create a next.config.js file using this command.

touch next.config.js

Now, we need to edit this file and include all our next-pwa configurations. Here is an example next.config.js that’ll help you get started:

Notice we have added the pwa config inside withPwa . On previous versions of Next, serving the service worker requires a custom server. But since Next 9+, this is not required. It’s much easier now! next-pwa will create the sw.js file and this file will served from the public folder in the production build.

4. Create manifest.json file

You can create a manifest.json file from this online tool. Make sure you generate the icons as well from this tool. We need them.

You will get a .zip download. Unzip. Copy the manifest.json from your download folder to your /public folder.

And copy the contents of /images from the download folder, to the /public folder of your project. You will see an icons folder :

5. Create the meta tags

We need to create a set of meta tags and add it into our pages using the <Head> component imported from next/head . I’ve referred to this repo for the required meta tags:

Here is an example of the meta tags required:

I’ve edited the components/nav.js to include this meta tags. Now, my nav.js looks like this. I have not removed any of the boilerplate codes to avoid any confusion.

You can generate the favicons and place them in your /public folder using this online tool:

6. Test your PWA!

Now, your app is PWA ready. We just need to test this. When we use next-pwa , the service workers are enabled only on production. So, we should build our app with npm run build or yarn build . You will see something like this after you’ve built.

And then start the production local server with npm run start or yarn start .

Go to http://localhost:3000 . If you are on Google Chrome, run a Lighthouse Audit. You should see something like this:

The one item that is marked red in the report below is:

This is because, PWAs need to run on HTTPS. Localhost is an exception. Deploy this to a server, and serve it via HTTPS, and you will get an audit something like this:

Success!

Out of the box, you get caching, offline support and a “Add to Home Screen” prompt will appear on Chrome ( mobile ). This enables users to use your PWA just like a native application. Enjoy your Progressive Web App!

Github Repo of this tutorial :