🌐 Web Development

PWA

Progressive Web App

Web apps that behave like native apps. Offline support, push notifications.

πŸ“– Detailed Explanation

A PWA (Progressive Web App) is a web application that is built with web technologies (HTML, CSS, JavaScript) but provides a user experience similar to a native app. It runs in the browser but can be installed on the home screen, works offline, and can send push notifications. It can be deployed with just a URL without app store registration, so updates take effect immediately.

The core technologies of PWAs are the Service Worker and the Web App Manifest. A Service Worker is a proxy script that runs between the browser and the network; it intercepts network requests to return cached responses and handles background sync and push notifications. The Web App Manifest is a JSON file that defines the app's metadata, such as its name, icons, and theme color.

PWAs are progressively enhanced. In browsers that do not support Service Workers they behave like an ordinary website, and in browsers that do, offline and install features are enabled. Thanks to this, a single codebase can support both web and mobile.

Workbox is a PWA development library from Google that simplifies writing Service Workers. Modern frameworks such as Next.js, Nuxt, and Vite can easily add PWA features through PWA plugins. The Lighthouse tool lets you check PWA compliance and see what to improve.

πŸ’» Code Example

// === manifest.json - Web App Manifest ===
{
    "name": "My PWA App",
    "short_name": "MyApp",
    "description": "PWA 예제 μ• ν”Œλ¦¬μΌ€μ΄μ…˜",
    "start_url": "/",
    "display": "standalone",
    "background_color": "#0f172a",
    "theme_color": "#a855f7",
    "orientation": "portrait-primary",
    "icons": [
        {
            "src": "/icons/icon-192.png",
            "sizes": "192x192",
            "type": "image/png",
            "purpose": "any maskable"
        },
        {
            "src": "/icons/icon-512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "screenshots": [
        {
            "src": "/screenshots/mobile.png",
            "sizes": "1080x1920",
            "type": "image/png",
            "form_factor": "narrow"
        }
    ]
}

// === index.html - Manifest 및 Service Worker 등둝 ===
<!DOCTYPE html>
<html>
<head>
    <link rel="manifest" href="/manifest.json">
    <meta name="theme-color" content="#a855f7">
    <!-- iOS Safari 지원 -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <link rel="apple-touch-icon" href="/icons/icon-192.png">
</head>
<body>
    <script>
    // Service Worker 등둝
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', async () => {
            try {
                const registration = await navigator.serviceWorker.register('/sw.js');
                console.log('SW registered:', registration.scope);
            } catch (error) {
                console.log('SW registration failed:', error);
            }
        });
    }
    </script>
</body>
</html>

// === sw.js - Service Worker (μΊμ‹œ μ „λž΅) ===
const CACHE_NAME = 'my-pwa-v1';
const STATIC_ASSETS = [
    '/',
    '/index.html',
    '/styles.css',
    '/app.js',
    '/icons/icon-192.png'
];

// μ„€μΉ˜ 이벀트 - 정적 μžμ› 캐싱
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            console.log('Caching static assets');
            return cache.addAll(STATIC_ASSETS);
        })
    );
    // λŒ€κΈ° 쀑인 Service Worker μ¦‰μ‹œ ν™œμ„±ν™”
    self.skipWaiting();
});

// ν™œμ„±ν™” 이벀트 - 였래된 μΊμ‹œ 정리
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames
                    .filter((name) => name !== CACHE_NAME)
                    .map((name) => caches.delete(name))
            );
        })
    );
    // λͺ¨λ“  ν΄λΌμ΄μ–ΈνŠΈμ— μ¦‰μ‹œ 적용
    self.clients.claim();
});

// Fetch 이벀트 - μΊμ‹œ μš°μ„  μ „λž΅ (Cache First)
self.addEventListener('fetch', (event) => {
    // API μš”μ²­μ€ λ„€νŠΈμ›Œν¬ μš°μ„ 
    if (event.request.url.includes('/api/')) {
        event.respondWith(networkFirst(event.request));
        return;
    }

    // 정적 μžμ›μ€ μΊμ‹œ μš°μ„ 
    event.respondWith(cacheFirst(event.request));
});

// μΊμ‹œ μš°μ„  μ „λž΅
async function cacheFirst(request) {
    const cachedResponse = await caches.match(request);
    if (cachedResponse) {
        return cachedResponse;
    }

    try {
        const networkResponse = await fetch(request);
        // μœ νš¨ν•œ μ‘λ‹΅λ§Œ μΊμ‹œ
        if (networkResponse.ok) {
            const cache = await caches.open(CACHE_NAME);
            cache.put(request, networkResponse.clone());
        }
        return networkResponse;
    } catch (error) {
        // μ˜€ν”„λΌμΈ 폴백 νŽ˜μ΄μ§€
        return caches.match('/offline.html');
    }
}

// λ„€νŠΈμ›Œν¬ μš°μ„  μ „λž΅
async function networkFirst(request) {
    try {
        const networkResponse = await fetch(request);
        const cache = await caches.open(CACHE_NAME);
        cache.put(request, networkResponse.clone());
        return networkResponse;
    } catch (error) {
        const cachedResponse = await caches.match(request);
        return cachedResponse || new Response('Offline', { status: 503 });
    }
}

// === ν‘Έμ‹œ μ•Œλ¦Ό 처리 ===
self.addEventListener('push', (event) => {
    const data = event.data?.json() || {
        title: 'μ•Œλ¦Ό',
        body: 'μƒˆλ‘œμš΄ μ†Œμ‹μ΄ μžˆμŠ΅λ‹ˆλ‹€.',
        icon: '/icons/icon-192.png'
    };

    event.waitUntil(
        self.registration.showNotification(data.title, {
            body: data.body,
            icon: data.icon,
            badge: '/icons/badge-72.png',
            data: data.url
        })
    );
});

// μ•Œλ¦Ό 클릭 처리
self.addEventListener('notificationclick', (event) => {
    event.notification.close();

    event.waitUntil(
        clients.openWindow(event.notification.data || '/')
    );
});

// === μ•±μ—μ„œ ν‘Έμ‹œ μ•Œλ¦Ό ꡬ독 ===
async function subscribeToPush() {
    const registration = await navigator.serviceWorker.ready;

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

    // μ„œλ²„μ— ꡬ독 정보 전솑
    await fetch('/api/push/subscribe', {
        method: 'POST',
        body: JSON.stringify(subscription),
        headers: { 'Content-Type': 'application/json' }
    });
}

πŸ—£οΈ Examples of Practical Conversations

PM

"We need to build both a native app and a web app, but we don't have the budget. What should we do?"

Developer

"Consider a PWA. You can build an app that behaves like a mobile app from a single web codebase. It supports home screen installation, offline support, and even push notifications, and there's no app store registration, so updates take effect immediately. Some native features (NFC, Bluetooth, etc.) are limited, though."

Colleague

"They say a PWA works offline. How is that possible?"

Developer

"The Service Worker intercepts network requests and returns cached responses. On the first visit it caches HTML, CSS, JS, images, and so on, and when offline it responds from the cache. Depending on the caching strategy, you can choose Cache First, Network First, and others."

Interviewer

"What are the installation requirements for a PWA?"

Candidate

"It must be served over HTTPS and needs a valid manifest.json file. The manifest requires the name, icons, start_url, and display properties. A Service Worker that handles the fetch event must also be registered. When these conditions are met, the browser shows an install prompt."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

HTTPS required: A PWA must be served over HTTPS, except on localhost. For security reasons, Service Workers only work in secure contexts. Test on localhost during development and apply an SSL certificate when deploying.

Cache invalidation: A Service Worker's cache persists until the user deletes it. When deploying a new version, change the cache name (versioning) and implement logic to clean up old caches. Otherwise users will keep seeing the old version.

iOS Safari limitations: iOS Safari supports PWA features only partially. Push notifications are supported from iOS 16.4, and background sync is still unsupported. Even when added to the home screen, only the address bar is hidden, and some features remain limited.

πŸ”— Related Terms

πŸ“š Learn More