You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13.4.19 PWA中Service Worker无法注册问题求助

Next.js 13.4.19 PWA Service Worker无法注册问题排查与解决

我当前正在使用Next.js 13.4.19开发PWA,Manifest等内容均可正常注册,但Service Worker无法注册,网站缓存也未被存储。

相关代码

layout.tsx

import { Inter } from 'next/font/google'
import React from "react";
const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'asdasdasdas',
  description: 'Generated by create next app',
  manifest: '/manifest.json',
  themeColor: "#3558f6",
}
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  )
}

next.config.js

const runtimeCaching = require('next-pwa/cache')
const withPWA = require('next-pwa')({
  dest: 'public',
  register: true,
  skipWaiting: true,
  sw: "/sw.js",
  runtimeCaching: [
    {
      urlPattern: "/",
      handler: 'NetworkFirst',
      options: {
        cacheName: 'pages-cache',
      },
    },
  ]
});

const nextConfig = withPWA({
  reactStrictMode: true,
});
module.exports = nextConfig;

问题截图

  • 缓存未存储状态:缓存未存储截图
  • Service Worker未注册状态:Service Worker未注册截图

解决方法

1. 确保next-pwa版本兼容

Next.js 13+(尤其是App Router)对next-pwa版本有要求,安装适配的最新版本:

npm install next-pwa@latest

2. 修正next.config.js配置

  • 移除手动指定的sw: "/sw.js",避免路径冲突,让插件自动生成正确的Service Worker文件
  • 添加开发环境禁用配置,确保仅生产环境启用:
const withPWA = require('next-pwa')({
  dest: 'public',
  register: true,
  skipWaiting: true,
  disable: process.env.NODE_ENV !== 'production', // 新增:开发环境禁用
  runtimeCaching: [
    {
      urlPattern: "/",
      handler: 'NetworkFirst',
      options: {
        cacheName: 'pages-cache',
      },
    },
  ]
});

3. 验证生产环境构建

next-pwa默认在开发环境不生成Service Worker,必须执行生产构建并启动服务:

npm run build
npm run start

之后再打开开发者工具查看状态。

4. 检查运行环境

Service Worker要求HTTPS环境(localhost除外),生产部署时确保域名已配置HTTPS。

5. 清理旧缓存

在开发者工具「Application」标签中,点击「Clear storage」下的「Clear site data」,彻底清理旧缓存与未注册的Service Worker后重新加载页面。

内容的提问来源于stack exchange,提问作者GeonwooLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:14:53