跳到內容
建置你的應用程式設定漸進式網頁應用程式 (PWA)

漸進式網頁應用程式 (PWA)

漸進式網頁應用程式 (PWA) 結合了網頁應用程式的觸及範圍和可訪問性,以及原生行動應用程式的功能和使用者體驗。透過 Next.js,你可以建立 PWA,在所有平台上提供無縫、類似應用程式的體驗,而無需多個程式碼庫或應用商店的批准。

PWA 允許你:

  • 即時部署更新,無需等待應用商店批准
  • 使用單一程式碼庫建立跨平台應用程式
  • 提供類似原生的功能,例如主畫面安裝和推播通知

使用 Next.js 建立 PWA

1. 建立 Web App Manifest

Next.js 提供內建支援,可使用 App Router 建立 web app manifest。你可以建立靜態或動態 manifest 檔案

例如,建立 app/manifest.tsapp/manifest.json 檔案

app/manifest.ts
import type { MetadataRoute } from 'next'
 
export default function manifest(): MetadataRoute.Manifest {
  return {
    name: 'Next.js PWA',
    short_name: 'NextPWA',
    description: 'A Progressive Web App built with Next.js',
    start_url: '/',
    display: 'standalone',
    background_color: '#ffffff',
    theme_color: '#000000',
    icons: [
      {
        src: '/icon-192x192.png',
        sizes: '192x192',
        type: 'image/png',
      },
      {
        src: '/icon-512x512.png',
        sizes: '512x512',
        type: 'image/png',
      },
    ],
  }
}

此檔案應包含關於名稱、圖示以及應如何在使用者裝置上顯示為圖示的資訊。這將允許使用者將你的 PWA 安裝到他們的主畫面,提供類似原生應用程式的體驗。

你可以使用像 favicon 產生器 的工具來建立不同的圖示集,並將產生的檔案放置在你的 public/ 資料夾中。

2. 實作 Web 推播通知

所有現代瀏覽器都支援 Web 推播通知,包括:

  • iOS 16.4+ (適用於安裝到主畫面的應用程式)
  • Safari 16 (適用於 macOS 13 或更高版本)
  • Chromium 架構的瀏覽器
  • Firefox

這使得 PWA 成為原生應用程式的可行替代方案。值得注意的是,你可以觸發安裝提示,而無需離線支援。

Web 推播通知允許你在使用者未主動使用你的應用程式時重新吸引他們。以下是如何在 Next.js 應用程式中實作它們:

首先,讓我們在 app/page.tsx 中建立主頁面元件。我們將其分解為更小的部分,以便更好地理解。首先,我們將新增一些我們需要的匯入和工具程式。即使引用的伺服器動作尚不存在也沒關係

'use client'
 
import { useState, useEffect } from 'react'
import { subscribeUser, unsubscribeUser, sendNotification } from './actions'
 
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
}

現在讓我們新增一個元件來管理訂閱、取消訂閱和發送推播通知。

function PushNotificationManager() {
  const [isSupported, setIsSupported] = useState(false)
  const [subscription, setSubscription] = useState<PushSubscription | null>(
    null
  )
  const [message, setMessage] = useState('')
 
  useEffect(() => {
    if ('serviceWorker' in navigator && 'PushManager' in window) {
      setIsSupported(true)
      registerServiceWorker()
    }
  }, [])
 
  async function registerServiceWorker() {
    const registration = await navigator.serviceWorker.register('/sw.js', {
      scope: '/',
      updateViaCache: 'none',
    })
    const sub = await registration.pushManager.getSubscription()
    setSubscription(sub)
  }
 
  async function subscribeToPush() {
    const registration = await navigator.serviceWorker.ready
    const sub = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(
        process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!
      ),
    })
    setSubscription(sub)
    const serializedSub = JSON.parse(JSON.stringify(sub))
    await subscribeUser(serializedSub)
  }
 
  async function unsubscribeFromPush() {
    await subscription?.unsubscribe()
    setSubscription(null)
    await unsubscribeUser()
  }
 
  async function sendTestNotification() {
    if (subscription) {
      await sendNotification(message)
      setMessage('')
    }
  }
 
  if (!isSupported) {
    return <p>Push notifications are not supported in this browser.</p>
  }
 
  return (
    <div>
      <h3>Push Notifications</h3>
      {subscription ? (
        <>
          <p>You are subscribed to push notifications.</p>
          <button onClick={unsubscribeFromPush}>Unsubscribe</button>
          <input
            type="text"
            placeholder="Enter notification message"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
          />
          <button onClick={sendTestNotification}>Send Test</button>
        </>
      ) : (
        <>
          <p>You are not subscribed to push notifications.</p>
          <button onClick={subscribeToPush}>Subscribe</button>
        </>
      )}
    </div>
  )
}

最後,讓我們建立一個元件來顯示針對 iOS 裝置的訊息,指示他們安裝到主畫面,並且只有在應用程式尚未安裝時才顯示此訊息。

function InstallPrompt() {
  const [isIOS, setIsIOS] = useState(false)
  const [isStandalone, setIsStandalone] = useState(false)
 
  useEffect(() => {
    setIsIOS(
      /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream
    )
 
    setIsStandalone(window.matchMedia('(display-mode: standalone)').matches)
  }, [])
 
  if (isStandalone) {
    return null // Don't show install button if already installed
  }
 
  return (
    <div>
      <h3>Install App</h3>
      <button>Add to Home Screen</button>
      {isIOS && (
        <p>
          To install this app on your iOS device, tap the share button
          <span role="img" aria-label="share icon">
            {' '}
            ⎋{' '}
          </span>
          and then "Add to Home Screen"
          <span role="img" aria-label="plus icon">
            {' '}
            ➕{' '}
          </span>.
        </p>
      )}
    </div>
  )
}
 
export default function Page() {
  return (
    <div>
      <PushNotificationManager />
      <InstallPrompt />
    </div>
  )
}

現在,讓我們建立此檔案呼叫的伺服器動作。

3. 實作伺服器動作

app/actions.ts 建立一個新檔案來包含你的動作。此檔案將處理建立訂閱、刪除訂閱和發送通知。

app/actions.ts
'use server'
 
import webpush from 'web-push'
 
webpush.setVapidDetails(
  '<mailto:your-email@example.com>',
  process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!,
  process.env.VAPID_PRIVATE_KEY!
)
 
let subscription: PushSubscription | null = null
 
export async function subscribeUser(sub: PushSubscription) {
  subscription = sub
  // In a production environment, you would want to store the subscription in a database
  // For example: await db.subscriptions.create({ data: sub })
  return { success: true }
}
 
export async function unsubscribeUser() {
  subscription = null
  // In a production environment, you would want to remove the subscription from the database
  // For example: await db.subscriptions.delete({ where: { ... } })
  return { success: true }
}
 
export async function sendNotification(message: string) {
  if (!subscription) {
    throw new Error('No subscription available')
  }
 
  try {
    await webpush.sendNotification(
      subscription,
      JSON.stringify({
        title: 'Test Notification',
        body: message,
        icon: '/icon.png',
      })
    )
    return { success: true }
  } catch (error) {
    console.error('Error sending push notification:', error)
    return { success: false, error: 'Failed to send notification' }
  }
}

發送通知將由我們的 service worker 處理,該 service worker 在步驟 5 中建立。

在生產環境中,你會希望將訂閱儲存在資料庫中,以便在伺服器重新啟動時保持持久性,並管理多個使用者的訂閱。

4. 產生 VAPID 金鑰

若要使用 Web 推播 API,你需要產生 VAPID 金鑰。最簡單的方法是直接使用 web-push CLI

首先,全域安裝 web-push

終端機
npm install -g web-push

透過執行以下命令產生 VAPID 金鑰

終端機
web-push generate-vapid-keys

複製輸出並將金鑰貼到你的 .env 檔案中

NEXT_PUBLIC_VAPID_PUBLIC_KEY=your_public_key_here
VAPID_PRIVATE_KEY=your_private_key_here

5. 建立 Service Worker

為你的 service worker 建立一個 public/sw.js 檔案

public/sw.js
self.addEventListener('push', function (event) {
  if (event.data) {
    const data = event.data.json()
    const options = {
      body: data.body,
      icon: data.icon || '/icon.png',
      badge: '/badge.png',
      vibrate: [100, 50, 100],
      data: {
        dateOfArrival: Date.now(),
        primaryKey: '2',
      },
    }
    event.waitUntil(self.registration.showNotification(data.title, options))
  }
})
 
self.addEventListener('notificationclick', function (event) {
  console.log('Notification click received.')
  event.notification.close()
  event.waitUntil(clients.openWindow('<https://your-website.com>'))
})

此 service worker 支援自訂圖片和通知。它處理傳入的推播事件和通知點擊。

  • 你可以使用 iconbadge 屬性為通知設定自訂圖示。
  • 可以調整 vibrate 模式,以便在支援的裝置上建立自訂震動警示。
  • 可以使用 data 屬性將額外資料附加到通知。

請記住徹底測試你的 service worker,以確保它在不同的裝置和瀏覽器上都能如預期般運作。此外,請務必將 notificationclick 事件偵聽器中的 'https://your-website.com' 連結更新為你的應用程式的適當 URL。

6. 新增至主畫面

步驟 2 中定義的 InstallPrompt 元件顯示針對 iOS 裝置的訊息,指示他們安裝到主畫面。

為了確保你的應用程式可以安裝到行動裝置主畫面,你必須具備:

  1. 有效的 web app manifest (在步驟 1 中建立)
  2. 透過 HTTPS 提供的網站

當符合這些條件時,現代瀏覽器將自動向使用者顯示安裝提示。你可以使用 beforeinstallprompt 提供自訂安裝按鈕,但是,我們不建議這樣做,因為它不是跨瀏覽器和平台通用的 (在 Safari iOS 上不起作用)。

7. 本機測試

為了確保你可以在本機檢視通知,請確保:

  • 你正在在本機使用 HTTPS 執行
    • 使用 next dev --experimental-https 進行測試
  • 你的瀏覽器 (Chrome、Safari、Firefox) 已啟用通知
    • 在本機收到提示時,接受使用通知的權限
    • 確保未針對整個瀏覽器全域停用通知
    • 如果你仍然看不到通知,請嘗試使用另一個瀏覽器進行偵錯

8. 保護你的應用程式安全

安全性是任何網頁應用程式的關鍵面向,尤其是對於 PWA 而言。Next.js 允許你使用 next.config.js 檔案設定安全性標頭。例如:

next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'X-Content-Type-Options',
            value: 'nosniff',
          },
          {
            key: 'X-Frame-Options',
            value: 'DENY',
          },
          {
            key: 'Referrer-Policy',
            value: 'strict-origin-when-cross-origin',
          },
        ],
      },
      {
        source: '/sw.js',
        headers: [
          {
            key: 'Content-Type',
            value: 'application/javascript; charset=utf-8',
          },
          {
            key: 'Cache-Control',
            value: 'no-cache, no-store, must-revalidate',
          },
          {
            key: 'Content-Security-Policy',
            value: "default-src 'self'; script-src 'self'",
          },
        ],
      },
    ]
  },
}

讓我們檢視每個選項:

  1. 全域標頭 (應用於所有路由)
    1. X-Content-Type-Options: nosniff:防止 MIME 類型嗅探,降低惡意檔案上傳的風險。
    2. X-Frame-Options: DENY:透過防止你的網站嵌入在 iframe 中來防禦點擊劫持攻擊。
    3. Referrer-Policy: strict-origin-when-cross-origin:控制在請求中包含多少參照位址資訊,在安全性和功能之間取得平衡。
  2. Service Worker 特定標頭
    1. Content-Type: application/javascript; charset=utf-8:確保 service worker 被正確解譯為 JavaScript。
    2. Cache-Control: no-cache, no-store, must-revalidate:防止快取 service worker,確保使用者始終獲得最新版本。
    3. Content-Security-Policy: default-src 'self'; script-src 'self':為 service worker 實作嚴格的內容安全策略,僅允許來自相同來源的腳本。

深入了解如何使用 Next.js 定義內容安全策略

下一步

  1. 探索 PWA 功能:PWA 可以利用各種 Web API 來提供進階功能。考慮探索諸如背景同步、定期背景同步或檔案系統存取 API 等功能,以增強你的應用程式。如需關於 PWA 功能的靈感和最新資訊,你可以參考像 What PWA Can Do Today 等資源。
  2. 靜態匯出: 如果你的應用程式不需要執行伺服器,而是使用檔案的靜態匯出,你可以更新 Next.js 設定以啟用此變更。在 Next.js 靜態匯出文件中了解更多資訊。但是,你將需要從伺服器動作轉移到呼叫外部 API,以及將你定義的標頭移動到你的代理伺服器。
  3. 離線支援:為了提供離線功能,一個選項是將 Serwist 與 Next.js 結合使用。你可以在他們的文件中找到如何將 Serwist 與 Next.js 整合的範例。注意:此插件目前需要 webpack 設定。
  4. 安全性考量:確保你的 service worker 已適當保護。這包括使用 HTTPS、驗證推播訊息的來源,以及實作適當的錯誤處理。
  5. 使用者體驗:考慮實作漸進式增強技術,以確保即使使用者的瀏覽器不支援某些 PWA 功能,你的應用程式也能良好運作。