Building Progressive Web Apps with Next.js

Reading Time: 7 min read

Introduction

Progressive Web Apps (PWAs) combine the best of web and mobile apps, offering fast, reliable, and engaging user experiences. With Next.js, you can easily build PWAs that take advantage of these benefits. In this post, we'll explore how to create a PWA using Next.js, focusing on performance, offline capabilities, and best practices.

What is a Progressive Web App?

A PWA is a type of application software delivered through the web, built using common web technologies including HTML, CSS, and JavaScript. PWAs are intended to work on any platform that uses a standards-compliant browser. Key features of PWAs include:

  1. Reliability: Load instantly and provide reliable performance, even under uncertain network conditions.
  2. Speed: Respond quickly to user interactions with smooth animations and no janky scrolling.
  3. Engagement: Feel like a natural app on the device, with an immersive user experience.

Setting Up a Next.js Project

  1. Create a Next.js App:

    Start by creating a new Next.js application.

    npx create-next-app my-pwa-app
    cd my-pwa-app
  2. Install Dependencies:

    Install the necessary dependencies for PWA features.

    npm install next-pwa
  3. Configure Next.js for PWA:

    Create or update your next.config.js file to include the PWA configuration.

    // next.config.js
    const withPWA = require('next-pwa')({
      dest: 'public',
    })
     
    module.exports = withPWA({
      // Next.js config options here
    })

Adding a Service Worker

A service worker is a script that your browser runs in the background, separate from a web page, enabling features that don't need a web page or user interaction. This includes features like push notifications and background sync.

  1. Create the Service Worker File:

    Create a public directory at the root of your project and add a service-worker.js file.

    // public/service-worker.js
    self.addEventListener('install', (event) => {
      console.log('Service Worker installing.')
    })
     
    self.addEventListener('activate', (event) => {
      console.log('Service Worker activating.')
    })
     
    self.addEventListener('fetch', (event) => {
      console.log('Fetching:', event.request.url)
    })

Adding a Manifest File

The web app manifest provides information about an application (such as name, author, icon, and description) in a JSON text file. The purpose of the manifest is to install web applications to the home screen of a device, providing users with quicker access and a richer experience.

  1. Create the Manifest File:

    Add a manifest.json file in the public directory.

    // public/manifest.json
    {
      "name": "My PWA App",
      "short_name": "PWA App",
      "start_url": ".",
      "display": "standalone",
      "background_color": "#ffffff",
      "description": "My awesome Progressive Web App!",
      "icons": [
        {
          "src": "/icon-192x192.png",
          "sizes": "192x192",
          "type": "image/png"
        },
        {
          "src": "/icon-512x512.png",
          "sizes": "512x512",
          "type": "image/png"
        }
      ]
    }
  2. Link the Manifest in Your App:

    Update your _app.js or _document.js to include the manifest file.

    // pages/_document.js
    import Document, { Html, Head, Main, NextScript } from 'next/document'
     
    class MyDocument extends Document {
      render() {
        return (
          <Html>
            <Head>
              <link rel="manifest" href="/manifest.json" />
              <link rel="apple-touch-icon" href="/icon-192x192.png" />
              <meta name="theme-color" content="#ffffff" />
            </Head>
            <body>
              <Main />
              <NextScript />
            </body>
          </Html>
        )
      }
    }
     
    export default MyDocument

Testing Your PWA

  1. Run Your Application:

    npm run dev
  2. Test with Lighthouse:

    Use Google Chrome's Lighthouse tool to test your PWA. Open Chrome DevTools, go to the Lighthouse tab, and run an audit. Lighthouse will provide insights and recommendations for improving your PWA.

Conclusion

Building a Progressive Web App with Next.js is straightforward and provides numerous benefits, including enhanced performance, offline capabilities, and a better user experience. By following the steps outlined in this post, you can create a PWA that leverages the power of Next.js and delivers a high-quality experience to your users.

For more detailed information, visit the Next.js documentation on PWA.

Go back Home.