DEV Community

Cover image for Integrating PWA in a Next.js App
Wafa Bergaoui
Wafa Bergaoui

Posted on • Updated on

Integrating PWA in a Next.js App

Introduction

Progressive Web Apps (PWAs) combine the best features of web and mobile applications, offering offline capabilities, push notifications, and the ability to install the app on a user’s device. For a detailed overview of PWAs, refer to my previous article The Evolution and Necessity of Progressive Web Apps.

This guide will take you through the steps to integrate a PWA into your Next.js application.

Steps to Integrate PWA in Next.js

1. Initial Setup

Ensure you have a Next.js app set up. If not, create one using:

npx create-next-app@latest pwa-app
cd pwa-app
Enter fullscreen mode Exit fullscreen mode

2. Install Dependencies

Install the next-pwa package to add PWA capabilities to your app:

npm install next-pwa
OR
yarn add next-pwa
Enter fullscreen mode Exit fullscreen mode

3. Configure next.config.js

Modify next.config.js to use the next-pwa plugin:

const withPWA = require('next-pwa')({
  dest: 'public',
  disable: process.env.NODE_ENV === 'development',
});

module.exports = withPWA({
  // Your existing Next.js configuration
});

Enter fullscreen mode Exit fullscreen mode

4. Create a Manifest File

  • Add a manifest.json file in the public directory. This file contains metadata about your web application, including details such as the app's name, short name, theme color, and icons.
  • You can create this file manually or use online tools like:

  • Example manifest.json:

{
  "name": "Progressive Web App",
  "short_name": "PWA",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
  • Save the manifest.json file in the /public directory of your project.

5. Service Worker Setup

The next-pwa plugin handles the creation and configuration of the service worker for you. Ensure the public directory is configured correctly for caching and offline capabilities.

6. Link Manifest in _document.js

Modify the _document.js file to include the manifest file and specify theme colors:

import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link rel="manifest" href="/manifest.json" />
          <meta name="theme-color" content="#000000" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

Enter fullscreen mode Exit fullscreen mode

7. Use VSCode Extension for PWA Development

Enhance your PWA development with the PWA Builder VSCode extension. This tool helps generate PWA assets, configure service workers, and more, streamlining the PWA integration process.

8. Check Validation

  • Run your app, and you should see an install prompt in the address bar, allowing users to install your PWA like a native app.

Image description

  • Verify your PWA using the PWA audit in Lighthouse (available in Chrome DevTools). Note that you need to deploy your app for this to work.

9. Additional Steps: Git Configuration

Add the following to your .gitignore to exclude files generated by next-pwa:

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

Enter fullscreen mode Exit fullscreen mode

10. Bonus: Optimize for Mobile Devices

  • To avoid unwanted scroll behavior on iOS Safari:
<Head>
  <meta name="viewport" content="initial-scale=1, viewport-fit=cover, width=device-width"></meta>
</Head>

Enter fullscreen mode Exit fullscreen mode
.someContainerClass {
  height: calc(100vh - env(safe-area-inset-bottom) - env(safe-area-inset-top));
}

@supports (-webkit-touch-callout: none) {
  .someContainerClass {
    height: -webkit-fill-available;
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Alternatively, set the container position:
.containerClass {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: 0;
}

Enter fullscreen mode Exit fullscreen mode
  • To hide the virtual keyboard on enter key press:
const hideVirtualKeyboard = () => {
  const inputElements = document.getElementsByTagName("input");
  Array.from(inputElements).forEach((input) => {
    input.blur();
  });
};

Enter fullscreen mode Exit fullscreen mode

Integrating PWA into your Next.js application not only improves the user experience but also increases engagement and accessibility, making it a valuable addition to any modern web project.

Conclusion

By following these steps and utilizing these resources, you can ensure your Next.js app leverages the full power of Progressive Web Apps, providing an enhanced, app-like experience for your users. This integration not only makes your application more accessible and engaging but also significantly improves performance and user satisfaction. Embrace the future of web development with PWAs in your Next.js projects!

Top comments (2)

Collapse
 
dreama profile image
Dream

Could you clarify how the next-pwa plugin handles offline capabilities and caching? I'm curious about the specifics.

Collapse
 
wafa_bergaoui profile image
Wafa Bergaoui

Without next-pwa, we need to manually create a service worker to handle caching strategies and offline capabilities. Here’s an example of how to do that:

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('my-cache').then(cache => {
      return cache.addAll([
        '/',
        '/index.html',
        '/styles.css',
        '/script.js',
        '/offline.html'
      ]);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    fetch(event.request).catch(() => caches.match('/offline.html'))
  );
});

Enter fullscreen mode Exit fullscreen mode

But, with next-pwa, the service worker is integrated, and it automatically manages caching and offline capabilities with simple configuration.