Build a PWA with Next.js and TypeScript

TiShow
2 min readAug 15, 2023

What is PWA ?

PWA stands for progressive web apps, a mechanism that allows web apps to be used like native apps.

next-pwa

Next-pwa is a library that makes it easy to implement PWA with Next.js, and it does things like caching behind the scenes that are implemented with serviceWorker.
Another well-known one is next-offline, but next-pwa is more frequently updated and easier to use for me personally, so I would like to use next-pwa.

1. Installation

Install with the following commands. (document)

## npm
npm i next-pwa

## yarn
yarn add next-pwa

2. Edit next.config.js

Create next.config.js in the root directory and I wrote the following

/** @type {import('next').NextConfig} */
const withPWA = require('next-pwa')({
dest: 'public',
register: true,
skipWaiting: true,
})

module.exports = withPWA({
// next.js config
reactStrictMode: false,
swcMinify: false,
})

There is a file named cache.js in next-pwa of node_modules, where cache settings are written. (By default, the cache is not cached by yarn dev.)

3. Edit manifest.json

In /public directory, edit manifest.json

{
"name": "PWA App",
"short_name": "App",
"description": "An example of a PWA using Next.js and TypeScript",
"start_url": "/",
"display": "standalone",
"background_color": "#FFFFFF",
"theme_color": "#FFFFFF",
"orientation": "portrait",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}

Above, “src”: “/android-chrome-192x192.png”, specifies the image placed in /public.

4. Create _document.tsx

Create _document.tsx in the src/pages directory and load icons, manifest.json, etc. in the <Head>.

<link rel="manifest" href="/manifest.json" />

5. Configuring .gitignore

If the PWA is successfully activated,

  • sw.js.
  • sw.js.map
  • vercel.svg
  • workbox***.js
  • workbox***.js.map

are generated in the public folder. Since these files are permanently updated, there is no need to send them to GitHub, so they should be removed.

Add the following in .gitignore

# PWA files
*/public/sw.js
**/public/workbox-.js
**/public/worker-.js
**/public/sw.js.map
**/public/workbox-.js.map
**/public/worker-.js.map

(Supplemental) Disabling PWA in development

You may want to disable PWA in the development environment, in which case, add disable to next.config.js.

/** @type {import('next').NextConfig} */
const withPWA = require('next-pwa')({
dest: 'public',
register: true,
skipWaiting: true,
disable: process.env.NODE_ENV === "development",
})

module.exports = withPWA({
// next.js config
reactStrictMode: false,
swcMinify: false,
})

Let’s actually execute it.

Execute the following command, in my case

## npm
npm run build
npm run dev

Happy coding !

--

--

TiShow

80% is the creation, the rest is depression. Developer and Data scientist. Looking for Physics Ph.D Twitter: @_t_i_show