How to create a Progressive Web App (PWA) with Next.js 14

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

· 4 min read
How to create a Progressive Web App (PWA) with Next.js 14 Banner Image
How to create a Progressive Web App (PWA) with Next.js 14 Banner Image

Introduction

Progressive Web Apps (PWAs) enhance web applications with features that offer a native app-like experience. Next.js 14 is a powerful framework for building these types of applications. In this guide, we'll walk through an in-depth process of creating a PWA with Next.js 14, including configurations, optimizations, and best practices.

Prerequisites

  • Basic knowledge of React and Next.js
  • Node.js and npm/yarn installed
  • A code editor like VS Code

Step 1: Setting Up Your Next.js 14 Project

  1. Create a New Next.js 14 Project Open your terminal and run:
npx create-next-app@latest my-pwa-app

or

yarn create next-app my-pwa-app

This command initializes a new Next.js application in a directory named my-pwa-app.

  1. Navigate to Your Project Directory
cd my-pwa-app

Step 2: Install Required Packages

Install next-pwa

The next-pwa package simplifies the integration of PWA features with Next.js:

npm install next-pwa

or

yarn add next-pwa

Optional: Install @next/bundle-analyzer

This package helps analyze your bundle size and optimize performance:

npm install @next/bundle-analyzer

or

yarn add @next/bundle-analyzer

Step 3: Configure Next.js 14 for PWA

1. Update next.config.js

Create or update the next.config.js file in the root directory:

// next.config.js
const withPWA = require('next-pwa')({
  dest: 'public',
  register: true,
  skipWaiting: true,
  runtimeCaching: [
    {
      urlPattern: /^https?.*/,
      handler: 'NetworkFirst',
      options: {
        cacheName: 'pages',
        expiration: {
          maxEntries: 100,
          maxAgeSeconds: 60 * 60 * 24 * 30, // 30 Days
        },
      },
    },
  ],
});

module.exports = withPWA({
  reactStrictMode: true,
  webpack(config, { isServer }) {
    if (!isServer) {
      config.resolve.fallback.fs = false;
    }
    return config;
  },
});
  • dest: Specifies the directory where service worker and related files are stored.
  • register and skipWaiting: Automatically register the service worker and skip waiting during updates.
  • runtimeCaching: Configures caching strategies.

2. Create public/manifest.json

This file describes your app’s appearance and behavior when installed on a device:

{
  "name": "My PWA App",
  "short_name": "PWA App",
  "description": "A Progressive Web App built with Next.js 14",
  "icons": [
    {
      "src": "/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "start_url": "/",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}
  • icons: Specifies the icons used for the PWA.
  • start_url: Defines the URL to open when the PWA is launched.
  • display: Determines the display mode (e.g., standalone or fullscreen).

3. Add PWA Icons

Create a public/icons directory and add your icon files:

  • icon-192x192.png
  • icon-512x512.png

Ensure these icons are optimized for performance and resolution.

4. Create a Service Worker

Create a public/sw.js file for custom service worker logic:

// public/sw.js
self.addEventListener('install', (event) => {
  console.log('Service Worker installing.');
  event.waitUntil(
    caches.open('static-v1').then((cache) => {
      return cache.addAll([
        '/',
        '/about',
        '/contact',
        '/icons/icon-192x192.png',
        '/icons/icon-512x512.png',
      ]);
    })
  );
});

self.addEventListener('activate', (event) => {
  console.log('Service Worker activating.');
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});
  • install: Caches essential files.
  • activate: Handles service worker activation.
  • fetch: Intercepts network requests to serve cached responses.

Step 4: Implement PWA Features

1. Add a Web App Manifest Link

Include the manifest file in your _document.js:

// 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" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

2. Test PWA Functionality

  • Run Your Application
npm run dev

or

yarn dev
  • Check PWA Features in Chrome DevTools
    • Go to chrome://inspect in Chrome.
    • Click “Open DevTools” for your app.
    • Navigate to the “Application” tab to inspect:
      • Manifest: Verify the manifest file is correctly linked.
      • Service Worker: Check the service worker registration and status.
      • Offline: Test offline capabilities by enabling “Offline” mode.

3. Optimize Performance

  • Analyze Bundle Size

Use the @next/bundle-analyzer to identify large dependencies and optimize them:

// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  reactStrictMode: true,
  // other Next.js config options
});

Run the analyzer:

ANALYZE=true npm run build

or

ANALYZE=true yarn build
  • Optimize Images

Use the next/image component for optimized image loading:

import Image from 'next/image';

function HomePage() {
  return (
    <div>
      <h1>My PWA App</h1>
      <Image
        src="/icons/icon-512x512.png"
        alt="App Icon"
        width={512}
        height={512}
      />
    </div>
  );
}

export default HomePage;

Step 5: Deploying Your PWA

Deploy to Vercel

Vercel is the recommended platform for deploying Next.js applications:Image: Vercel deployment process.

  • Push your code to a Git repository (e.g., GitHub).
  • Connect your repository to Vercel and deploy.

Other Deployment Options

You can also deploy to platforms like Netlify or AWS. Ensure you configure service worker support and static file serving appropriately.

Conclusion

You’ve successfully created a Progressive Web App with Next.js 14. This guide covered PWA configuration, optimization, and deployment to help you build a fast, reliable, and engaging web app.

Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.

Copyright © 2024 Mbloging. All rights reserved.