Next.js course ยท Module 8: Deployment and Production

Progressive Web Apps and Service Workers

14 min read ยท
In this lesson11

Progressive Web Apps (PWA) are modern web applications that combine the best features of web and native applications. Next.js offers excellent support for PWAs, allowing the creation of fast, reliable, and engaging applications that also work offline. In this module, we will learn how to implement PWAs in Next.js using Service Workers.

What are Progressive Web Apps?

Progressive Web Apps are web applications that use modern web technologies to provide users with an experience similar to native applications. The key features of PWAs are:

  1. Progressive - work for every user, regardless of the browser
  2. Responsive - adapt to different screen sizes
  3. Connectivity Independent - work offline or with a poor connection
  4. App-like - provide navigation and interactions like in native applications
  5. Fresh - always up to date thanks to Service Worker
  6. Safe - served over HTTPS
  7. Discoverable - identified as "applications" by search engines
  8. Re-engageable - enable re-engagement via push notifications
  9. Installable - can be installed on a device without an app store
  10. Linkable - easy sharing via URL

Service Workers - the foundation of PWA

Service Workers are JavaScript scripts that run in the background, independently of the application's main thread. They allow:

  • Caching resources for offline work
  • Intercepting and modifying network requests
  • Sending push notifications
  • Background synchronization
  • Application installation

Service Worker lifecycle

  1. Registration - registering the Service Worker
  2. Installation - installing and configuring the cache
  3. Activation - activating and clearing old caches
  4. Fetch - intercepting network requests
  5. Update - updating to a new version

PWA implementation in Next.js

1. Installing and configuring next-pwa

The easiest way to add PWA functionality to a Next.js application is to use the package next-pwa:

npm install next-pwa
# or
yarn add next-pwa

Update next.config.js:

// next.config.js
const withPWA = require('next-pwa')({
  dest: 'public',
  register: true,
  skipWaiting: true,
  disable: process.env.NODE_ENV === 'development', // Disable in development
  runtimeCaching: [
    {
      urlPattern: /^https?.*/,
      handler: 'NetworkFirst',
      options: {
        cacheName: 'offlineCache',
        expiration: {
          maxEntries: 200,
          maxAgeSeconds: 24 * 60 * 60, // 24 hours
        },
      },
    },
  ],
});

module.exports = withPWA({
  // Your standard Next.js configuration
  reactStrictMode: true,
  swcMinify: true,
});

2. Application manifest

The manifest is a JSON file that contains metadata about the PWA application. Create the file public/manifest.json:

{
  "name": "My PWA Application",
  "short_name": "MyApp",
  "description": "Example Progressive Web App built with Next.js",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "orientation": "portrait-primary",
  "icons": [
    {
      "src": "/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png",
      "purpose": "maskable any"
    },
    {
      "src": "/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose": "maskable any"
    }
  ],
  "categories": ["productivity", "utilities"],
  "screenshots": [
    {
      "src": "/screenshots/desktop.png",
      "sizes": "1280x720",
      "type": "image/png",
      "form_factor": "wide"
    },
    {
      "src": "/screenshots/mobile.png",
      "sizes": "750x1334",
      "type": "image/png",
      "form_factor": "narrow"
    }
  ]
}

3. Adding meta tags to HTML

Update the main application layout to add the necessary meta tags:

// app/layout.tsx
import type { Metadata, Viewport } from 'next';

export const metadata: Metadata = {
  title: 'My PWA Application',
  description: 'Example Progressive Web App',
  generator: 'Next.js',
  manifest: '/manifest.json',
  keywords: ['nextjs', 'pwa', 'react'],
  authors: [
    { name: 'Your Team' },
  ],
  creator: 'Your Team',
  formatDetection: {
    email: false,
    address: false,
    telephone: false,
  },
  metadataBase: new URL('https://your-domain.com'),
  alternates: {
    canonical: '/',
  },
  openGraph: {
    type: 'website',
    siteName: 'My PWA Application',
    title: {
      default: 'My PWA Application',
      template: '%s | My PWA Application',
    },
    description: 'Example Progressive Web App',
  },
  twitter: {
    card: 'summary',
    title: {
      default: 'My PWA Application',
      template: '%s | My PWA Application',
    },
    description: 'Example Progressive Web App',
  },
  appleWebApp: {
    title: 'My PWA Application',
    statusBarStyle: 'default',
    capable: true,
  },
};

export const viewport: Viewport = {
  themeColor: [
    { media: '(prefers-color-scheme: light)', color: '#ffffff' },
    { media: '(prefers-color-scheme: dark)', color: '#000000' },
  ],
  minimumScale: 1,
  initialScale: 1,
  width: 'device-width',
  shrinkToFit: false,
  viewportFit: 'cover',
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <head>
        <link rel="icon" href="/favicon.ico" />
        <link rel="apple-touch-icon" href="/icons/icon-192x192.png" />
      </head>
      <body>
        {children}
      </body>
    </html>
  );
}

Custom Service Worker implementation

If you need more control over the Service Worker, you can create your own implementation:

1. Creating a Service Worker

// public/sw.js
const CACHE_NAME = 'my-app-v1';
const urlsToCache = [
  '/',
  '/static/js/bundle.js',
  '/static/css/main.css',
  '/manifest.json',
];

// Install event - resource caching
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Cache opened');
        return cache.addAll(urlsToCache);
      })
      .then(() => {
        // Forces activation of the new Service Worker
        return self.skipWaiting();
      })
  );
});

// Activate event - clearing old caches
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            console.log('Removing old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    }).then(() => {
      // Take control over all clients
      return self.clients.claim();
    })
  );
});

// Fetch event - cache-first strategy
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        // Return from cache if available
        if (response) {
          return response;
        }

        // Otherwise fetch from the network
        return fetch(event.request).then((response) => {
          // Check if we received a valid response
          if (!response || response.status !== 200 || response.type !== 'basic') {
            return response;
          }

          // Clone the response
          const responseToCache = response.clone();

          caches.open(CACHE_NAME)
            .then((cache) => {
              cache.put(event.request, responseToCache);
            });

          return response;
        }).catch(() => {
          // If the request failed, return the offline page
          if (event.request.destination === 'document') {
            return caches.match('/offline.html');
          }
        });
      })
  );
});

// Background sync
self.addEventListener('sync', (event) => {
  if (event.tag === 'background-sync') {
    event.waitUntil(doBackgroundSync());
  }
});

function doBackgroundSync() {
  // Background synchronization implementation
  return fetch('/api/sync')
    .then(response => response.json())
    .then(data => {
      console.log('Background sync completed:', data);
    })
    .catch(err => {
      console.error('Background sync failed:', err);
    });
}

2. Registration Service Worker

// lib/serviceWorker.ts
export function registerSW() {
  if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js')
        .then((registration) => {
          console.log('SW registered: ', registration);

          // Checking for updates
          registration.addEventListener('updatefound', () => {
            const newWorker = registration.installing;
            if (newWorker) {
              newWorker.addEventListener('statechange', () => {
                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                  // A new Service Worker is available
                  showUpdateAvailableNotification();
                }
              });
            }
          });
        })
        .catch((error) => {
          console.log('SW registration failed: ', error);
        });
    });
  }
}

export function unregisterSW() {
  if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then((registration) => {
      registration.unregister();
    });
  }
}

function showUpdateAvailableNotification() {
  // Show notification about available update
  if (confirm('A new version of the application is available. Would you like to update it?')) {
    window.location.reload();
  }
}

3. Usage in a component

// app/page.tsx
'use client';

import { useEffect } from 'react';
import { registerSW } from '@/lib/serviceWorker';

export default function HomePage() {
  useEffect(() => {
    registerSW();
  }, []);

  return (
    <div>
      <h1>My PWA Application</h1>
      <p>Welcome to the Progressive Web App!</p>
    </div>
  );
}

Advanced caching strategies

Different content types require different caching strategies:

1. Cache First - for static resources

// Cache First strategy
self.addEventListener('fetch', (event) => {
  if (event.request.destination === 'image' ||
      event.request.destination === 'style' ||
      event.request.destination === 'script') {
    event.respondWith(
      caches.match(event.request).then((cachedResponse) => {
        return cachedResponse || fetch(event.request).then((response) => {
          const responseClone = response.clone();
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(event.request, responseClone);
          });
          return response;
        });
      })
    );
  }
});

2. Network First - for dynamic content

// Network First strategy
self.addEventListener('fetch', (event) => {
  if (event.request.url.includes('/api/')) {
    event.respondWith(
      fetch(event.request)
        .then((response) => {
          const responseClone = response.clone();
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(event.request, responseClone);
          });
          return response;
        })
        .catch(() => {
          return caches.match(event.request);
        })
    );
  }
});

3. Stale While Revalidate - for frequently changing content

// Stale While Revalidate strategy
self.addEventListener('fetch', (event) => {
  if (event.request.url.includes('/news/')) {
    event.respondWith(
      caches.match(event.request).then((cachedResponse) => {
        const fetchPromise = fetch(event.request).then((networkResponse) => {
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(event.request, networkResponse.clone());
          });
          return networkResponse;
        });

        return cachedResponse || fetchPromise;
      })
    );
  }
});

Implementing offline functionality

1. Offline page

Create a dedicated offline page:

// app/offline/page.tsx
export default function OfflinePage() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <div className="text-center">
        <div className="mb-4">
          <svg className="mx-auto h-16 w-16 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192L5.636 18.364M12 2.25a9.75 9.75 0 1 0 0 19.5 9.75 9.75 0 0 0 0-19.5Z" />
          </svg>
        </div>
        <h1 className="text-2xl font-bold text-gray-900 mb-2">You are offline</h1>
        <p className="text-gray-600 mb-4">
          We cannot connect to the internet. Check your connection and try again.
        </p>
        <button
          onClick={() => window.location.reload()}
          className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded"
        >
          Try again
        </button>
      </div>
    </div>
  );
}

2. Detecting online/offline state

// hooks/useOnlineStatus.ts
import { useState, useEffect } from 'react';

export function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    function handleOnline() {
      setIsOnline(true);
    }

    function handleOffline() {
      setIsOnline(false);
    }

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Check initial state
    setIsOnline(navigator.onLine);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return isOnline;
}

3. Connection status indicator component

// components/OnlineStatusIndicator.tsx
'use client';

import { useOnlineStatus } from '@/hooks/useOnlineStatus';

export default function OnlineStatusIndicator() {
  const isOnline = useOnlineStatus();

  if (isOnline) {
    return null; // Don't show anything when there is a connection
  }

  return (
    <div className="fixed top-0 left-0 right-0 bg-red-500 text-white text-center py-2 z-50">
      <span className="text-sm font-medium">
        No internet connection - you are operating in offline mode
      </span>
    </div>
  );
}

Push Notifications

Push notifications allow user re-engagement:

1. Subscription registration

// lib/notifications.ts

// Function to convert VAPID key
function urlBase64ToUint8Array(base64String: string) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

export async function subscribeToPushNotifications() {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
    throw new Error('Push notifications are not supported');
  }

  const registration = await navigator.serviceWorker.ready;

  // Check if a subscription already exists
  let subscription = await registration.pushManager.getSubscription();

  if (!subscription) {
    const vapidPublicKey = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
    if (!vapidPublicKey) {
      throw new Error('VAPID public key is not configured');
    }

    subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),
    });
  }

  // Send subscription to the server
  await fetch('/api/notifications/subscribe', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(subscription),
  });

  return subscription;
}

export async function unsubscribeFromPushNotifications() {
  const registration = await navigator.serviceWorker.ready;
  const subscription = await registration.pushManager.getSubscription();

  if (subscription) {
    await subscription.unsubscribe();

    // Notify the server about subscription cancellation
    await fetch('/api/notifications/unsubscribe', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(subscription),
    });
  }
}

2. Handling push notifications in Service Worker

// public/sw.js (addition to previous code)

// Handling push notifications
self.addEventListener('push', (event) => {
  const options = {
    body: 'You have a new message!',
    icon: '/icons/icon-192x192.png',
    badge: '/icons/badge-72x72.png',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      primaryKey: 1
    },
    actions: [
      {
        action: 'explore',
        title: 'See more',
        icon: '/icons/checkmark.png'
      },
      {
        action: 'close',
        title: 'Close',
        icon: '/icons/xmark.png'
      }
    ]
  };

  if (event.data) {
    const data = event.data.json();
    options.body = data.body || options.body;
    options.data = { ...options.data, ...data.data };
  }

  event.waitUntil(
    self.registration.showNotification('My PWA Application', options)
  );
});

// Handling notification click
self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  if (event.action === 'explore') {
    // Open a specific page
    event.waitUntil(
      clients.openWindow('/notifications')
    );
  } else if (event.action === 'close') {
    // Close the notification
    return;
  } else {
    // Default action - open the main page
    event.waitUntil(
      clients.openWindow('/')
    );
  }
});

3. API endpoint for sending notifications

// app/api/notifications/send/route.ts
import { NextRequest, NextResponse } from 'next/server';
import webpush from 'web-push';
import { prisma } from '@/lib/prisma';

// VAPID configuration
webpush.setVapidDetails(
  'mailto:your-email@example.com',
  process.env.VAPID_PUBLIC_KEY!,
  process.env.VAPID_PRIVATE_KEY!
);

export async function POST(request: NextRequest) {
  try {
    const { title, body, url } = await request.json();

    // Fetch all subscriptions from the database
    const subscriptions = await prisma.pushSubscription.findMany();

    const payload = JSON.stringify({
      title,
      body,
      url,
      icon: '/icons/icon-192x192.png',
    });

    // Send notifications to all subscriptions
    const promises = subscriptions.map(async (subscription) => {
      try {
        await webpush.sendNotification(
          {
            endpoint: subscription.endpoint,
            keys: {
              p256dh: subscription.p256dh,
              auth: subscription.auth,
            },
          },
          payload
        );
      } catch (error) {
        console.error('Error sending notification:', error);

        // If the subscription is invalid, remove it
        if (error.statusCode === 410) {
          await prisma.pushSubscription.delete({
            where: { id: subscription.id },
          });
        }
      }
    });

    await Promise.all(promises);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error sending notifications:', error);
    return NextResponse.json(
      { error: 'Failed to send notifications' },
      { status: 500 }
    );
  }
}

Installing the application (Add to Home Screen)

1. InstallPrompt component

// components/InstallPrompt.tsx
'use client';

import { useState, useEffect } from 'react';

interface BeforeInstallPromptEvent extends Event {
  readonly platforms: string[];
  readonly userChoice: Promise<{
    outcome: 'accepted' | 'dismissed';
    platform: string;
  }>;
  prompt(): Promise<void>;
}

export default function InstallPrompt() {
  const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);
  const [showInstallButton, setShowInstallButton] = useState(false);

  useEffect(() => {
    const handler = (e: Event) => {
      // Prevent automatic prompt display
      e.preventDefault();
      setDeferredPrompt(e as BeforeInstallPromptEvent);
      setShowInstallButton(true);
    };

    window.addEventListener('beforeinstallprompt', handler);

    // Check if the application is already installed
    window.addEventListener('appinstalled', () => {
      console.log('PWA has been installed');
      setShowInstallButton(false);
      setDeferredPrompt(null);
    });

    return () => {
      window.removeEventListener('beforeinstallprompt', handler);
    };
  }, []);

  const handleInstallClick = async () => {
    if (!deferredPrompt) return;

    // Show the installation prompt
    deferredPrompt.prompt();

    // Wait for user choice
    const { outcome } = await deferredPrompt.userChoice;

    if (outcome === 'accepted') {
      console.log('User accepted the installation');
    } else {
      console.log('User rejected the installation');
    }

    setDeferredPrompt(null);
    setShowInstallButton(false);
  };

  if (!showInstallButton) {
    return null;
  }

  return (
    <div className="fixed bottom-4 right-4 bg-blue-500 text-white p-4 rounded-lg shadow-lg">
      <div className="flex items-center space-x-3">
        <div>
          <h3 className="font-semibold">Install application</h3>
          <p className="text-sm opacity-90">Add to home screen for faster access</p>
        </div>
        <div className="flex space-x-2">
          <button
            onClick={handleInstallClick}
            className="bg-white text-blue-500 px-3 py-1 rounded text-sm font-medium"
          >
            Install
          </button>
          <button
            onClick={() => setShowInstallButton(false)}
            className="text-white opacity-75 hover:opacity-100"
          >
            ร—
          </button>
        </div>
      </div>
    </div>
  );
}

Testing PWA

1. Lighthouse Audit

Lighthouse is a Google tool for PWA audits. You can run it:

2. PWA Builder

Microsoft PWA Builder (https://www.pwabuilder.com/) is a tool for testing and building PWAs.

3. Manual testing

// utils/pwa-test.ts
export function testPWAFeatures() {
  const results = {
    serviceWorker: 'serviceWorker' in navigator,
    pushNotifications: 'PushManager' in window,
    notifications: 'Notification' in window,
    backgroundSync: 'serviceWorker' in navigator && 'sync' in window.ServiceWorkerRegistration.prototype,
    installPrompt: true, // Detected dynamically
    offline: 'onLine' in navigator,
  };

  console.table(results);
  return results;
}

PWA best practices

1. Performance

  • Use appropriate caching strategies
  • Optimize bundle size
  • Implement lazy loading
  • Use Service Worker to preload critical resources

2. User Experience

  • Ensure smooth transitions between online/offline modes
  • Implement skeleton screens during loading
  • Add loading indicators
  • Provide clear connection status messages

3. Security

  • Always use HTTPS
  • Validate all input data
  • Implement Content Security Policy (CSP)
  • Regularly update the Service Worker

4. Accessibility

  • Provide screen reader support
  • Use appropriate color contrasts
  • Implement keyboard navigation
  • Add appropriate aria-labels

Summary

Progressive Web Apps are a powerful technology that allows creating web applications with functionality close to native applications. Next.js with the next-pwa package or a custom Service Worker implementation offers all the tools needed to create a fully functional PWA.

Key elements of a PWA implementation in Next.js:

  1. Service Worker - for caching and offline work
  2. Web App Manifest - for application metadata
  3. HTTPS - required for PWA
  4. Responsive Design - for different devices
  5. Push Notifications - for user engagement
  6. Install Prompts - for installation on a device

PWAs allow delivering a better user experience, increasing engagement, and improving application performance, especially in conditions of poor internet connection.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Demo: Progressive Web Apps and Service Workers
interface PWAFeature {
  id: string;
  name: string;
  icon: string;
  description: string;
  status: 'supported' | 'partial' | 'not-supported';
  code: string;
}

function PWADemo() {
  const [activeTab, setActiveTab] = useState<'features' | 'manifest' | 'service-worker' | 'install'>('features');
  const [installStep, setInstallStep] = useState(0);
  const [cacheStrategy, setCacheStrategy] = useState<'cache-first' | 'network-first' | 'stale-while-revalidate'>('cache-first');

  const features: PWAFeature[] = [
    { id: 'offline', name: 'Offline Support', icon: 'OFF', description: 'Works without an internet connection',
      status: 'supported', code: "// Service Worker cache\nself.addEventListener('fetch', (event) => {\n  event.respondWith(\n    caches.match(event.request)\n      .then(cached => cached || fetch(event.request))\n  );\n});" },
    { id: 'install', name: 'Installation', icon: 'INS', description: 'Can be added to the home screen',
      status: 'supported', code: "// manifest.json\n{\n  \"name\": \"My PWA\",\n  \"short_name\": \"PWA\",\n  \"start_url\": \"/\",\n  \"display\": \"standalone\",\n  \"background_color\": \"#0f0f23\",\n  \"theme_color\": \"#64ffda\"\n}" },
    { id: 'push', name: 'Push Notifications', icon: 'PUS', description: 'Notifications even when the app is closed',
      status: 'supported', code: "// Subscribe to push\nconst registration = await navigator.serviceWorker.ready;\nconst subscription = await registration.pushManager.subscribe({\n  userVisibleOnly: true,\n  applicationServerKey: VAPID_PUBLIC_KEY,\n});" },
    { id: 'sync', name: 'Background Sync', icon: 'SYN', description: 'Background data synchronization',
      status: 'partial', code: "// Background sync\nnavigator.serviceWorker.ready.then(reg => {\n  reg.sync.register('sync-data');\n});" },
    { id: 'share', name: 'Web Share API', icon: 'SHR', description: 'Native content sharing',
      status: 'supported', code: "// Share API\nawait navigator.share({\n  title: 'My App',\n  text: 'Check this out!',\n  url: window.location.href,\n});" },
  ];

  const [selectedFeature, setSelectedFeature] = useState(features[0]);

  const statusColors: Record<string, string> = { supported: '#10b981', partial: '#f59e0b', 'not-supported': '#ef4444' };

  const manifest = {
    name: "Quantum City PWA",
    short_name: "QuantumPWA",
    description: "Advanced PWA application",
    start_url: "/",
    display: "standalone",
    background_color: "#0f0f23",
    theme_color: "#64ffda",
    icons: [
      { src: "/icon-192.png", sizes: "192x192", type: "image/png" },
      { src: "/icon-512.png", sizes: "512x512", type: "image/png" },
    ],
  };

  const cacheStrategies: Record<string, { desc: string; code: string }> = {
    'cache-first': {
      desc: 'Checks the cache first, then the network',
      code: "event.respondWith(\n  caches.match(event.request).then(cached =>\n    cached || fetch(event.request).then(response => {\n      const clone = response.clone();\n      caches.open('v1').then(cache => cache.put(event.request, clone));\n      return response;\n    })\n  )\n);",
    },
    'network-first': {
      desc: 'Network first, cache as fallback',
      code: "event.respondWith(\n  fetch(event.request)\n    .then(response => {\n      const clone = response.clone();\n      caches.open('v1').then(cache => cache.put(event.request, clone));\n      return response;\n    })\n    .catch(() => caches.match(event.request))\n);",
    },
    'stale-while-revalidate': {
      desc: 'Instantly from cache, updates in the background',
      code: "event.respondWith(\n  caches.open('v1').then(cache =>\n    cache.match(event.request).then(cached => {\n      const fetched = fetch(event.request)\n        .then(response => {\n          cache.put(event.request, response.clone());\n          return response;\n        });\n      return cached || fetched;\n    })\n  )\n);",
    },
  };

  const installSteps = [
    { title: 'next-pwa', desc: 'npm install next-pwa' },
    { title: 'next.config.js', desc: 'next-pwa configuration in next.config.js' },
    { title: 'manifest.json', desc: 'Create the public/manifest.json file' },
    { title: 'Icons', desc: 'Add 192x192 and 512x512 icons' },
    { title: 'Meta tags', desc: 'Add PWA meta tags in layout.tsx' },
    { title: 'Done!', desc: 'The PWA application is ready' },
  ];

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>PWA & Service Workers</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Progressive Web Apps in Next.js</p>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '24px' }}>
        {[
          { id: 'features' as const, label: 'PWA Features' },
          { id: 'manifest' as const, label: 'Manifest' },
          { id: 'service-worker' as const, label: 'Service Worker' },
          { id: 'install' as const, label: 'Installation' },
        ].map(tab => (
          <button key={tab.id} onClick={() => setActiveTab(tab.id)} style={{
            padding: '10px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
            background: activeTab === tab.id ? '#64ffda' : '#1a1a2e', color: activeTab === tab.id ? '#0f0f23' : '#8892b0', fontWeight: 'bold',
          }}>{tab.label}</button>
        ))}
      </div>

      {activeTab === 'features' && (
        <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: '20px' }}>
          <div style={{ display: 'grid', gap: '8px', alignContent: 'start' }}>
            {features.map(f => (
              <div key={f.id} onClick={() => setSelectedFeature(f)} style={{
                padding: '12px', borderRadius: '8px', cursor: 'pointer',
                background: selectedFeature.id === f.id ? '#1a2a3e' : '#1a1a2e',
                border: selectedFeature.id === f.id ? '1px solid #64ffda' : '1px solid #333',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <strong>{f.name}</strong>
                  <span style={{ fontSize: '11px', padding: '2px 8px', borderRadius: '12px', background: statusColors[f.status] + '30', color: statusColors[f.status] }}>{f.status}</span>
                </div>
                <div style={{ fontSize: '12px', color: '#8892b0', marginTop: '4px' }}>{f.description}</div>
              </div>
            ))}
          </div>
          <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
            <h3 style={{ color: '#64ffda', marginTop: 0 }}>{selectedFeature.name}</h3>
            <p style={{ color: '#8892b0' }}>{selectedFeature.description}</p>
            <pre style={{ background: '#0f0f23', padding: '12px', borderRadius: '6px', fontSize: '12px', color: '#e0e0e0', overflow: 'auto', whiteSpace: 'pre-wrap' }}>{selectedFeature.code}</pre>
          </div>
        </div>
      )}

      {activeTab === 'manifest' && (
        <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
          <h3 style={{ color: '#64ffda', marginTop: 0 }}>manifest.json</h3>
          <pre style={{ background: '#0f0f23', padding: '16px', borderRadius: '8px', fontSize: '13px', color: '#e0e0e0', overflow: 'auto' }}>
            {JSON.stringify(manifest, null, 2)}
          </pre>
        </div>
      )}

      {activeTab === 'service-worker' && (
        <div>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
            {(Object.keys(cacheStrategies) as Array<keyof typeof cacheStrategies>).map(s => (
              <button key={s} onClick={() => setCacheStrategy(s as any)} style={{
                padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
                background: cacheStrategy === s ? '#7c3aed' : '#1a1a2e', color: '#fff',
              }}>{s}</button>
            ))}
          </div>
          <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
            <p style={{ color: '#8892b0' }}>{cacheStrategies[cacheStrategy].desc}</p>
            <pre style={{ background: '#0f0f23', padding: '16px', borderRadius: '8px', fontSize: '12px', color: '#e0e0e0', overflow: 'auto', whiteSpace: 'pre-wrap' }}>{cacheStrategies[cacheStrategy].code}</pre>
          </div>
        </div>
      )}

      {activeTab === 'install' && (
        <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
          <h3 style={{ color: '#64ffda', marginTop: 0 }}>PWA Configuration in Next.js</h3>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
            {installSteps.map((s, i) => (
              <button key={i} onClick={() => setInstallStep(i)} style={{
                padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer', fontSize: '12px',
                background: installStep === i ? '#64ffda' : i < installStep ? '#10b98130' : '#333',
                color: installStep === i ? '#0f0f23' : '#8892b0',
              }}>{i + 1}. {s.title}</button>
            ))}
          </div>
          <div style={{ padding: '16px', background: '#0f0f23', borderRadius: '8px' }}>
            <strong style={{ color: '#64ffda' }}>{installSteps[installStep].title}</strong>
            <p style={{ color: '#8892b0', marginBottom: 0 }}>{installSteps[installStep].desc}</p>
          </div>
        </div>
      )}
    </div>
  );
}

export default PWADemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What must a Next.js application include to qualify as a Progressive Web App?

  1. QuestionProgressive Web Apps (PWA)

Useful articles