带有 NextJs 的 FCM

FCM with NextJs

我正在尝试将 FCM 与 next.js 集成......但它显示以下错误。谁能帮我处理 next.config.js 文件?

FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
    at WindowController.eval (webpack-internal:///./node_modules/@firebase/messaging/dist/index.esm.js:1053:45)
    at step (webpack-internal:///./node_modules/tslib/tslib.es6.js:124:23)
    at Object.eval [as throw] (webpack-internal:///./node_modules/tslib/tslib.es6.js:105:53)
    at rejected (webpack-internal:///./node_modules/tslib/tslib.es6.js:96:65)

你不需要配置 next.config.js,你只需要在 Public 文件夹中添加名为 firebase-messaging-sw.js[=13 的 serviceWorker =]

他们在文档中提到了以下内容:

The messaging service requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token. You can add meaningful content to the file later in the client configuration process.

访问:Access the registration token

您的 serviceWorker 应如下所示:

importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
 
firebase.initializeApp({
  apiKey: 'api-key',
  authDomain: 'project-id.firebaseapp.com',
  databaseURL: 'https://project-id.firebaseio.com',
  projectId: 'project-id',
  storageBucket: 'project-id.appspot.com',
  messagingSenderId: 'sender-id',
  appId: 'app-id',
  measurementId: 'G-measurement-id',
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();



messaging.onBackgroundMessage(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

记得在你的 initializeApp 上使用 ENV

Example with nextjs, Firebase V9 cloud messaging

生成VapidKey 添加项目的配置变量 之后,你执行 de npm 运行 dev。它会在控制台中出现令牌,您可以使用该令牌发送 test message。并且会发送前台和后台通知。