我正试图将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 的serviceWorker即可
他们在文件中提到了以下内容:
消息服务需要一个firebase-messaging-sw.js文件。除非您已经有一个firebase-messaging-sw.js文件,否则在检索令牌之前,创建一个具有该名称的空文件并将其放置在域的根目录中。您可以在稍后的客户端配置过程中将有意义的内容添加到文件中。
访问:访问注册令牌
你的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
nextjs、Firebase V9云消息示例
生成VapidKey添加项目的配置变量之后,您执行de npm run dev。它将在控制台中显示令牌,您可以使用该令牌发送测试消息。并且它将发送前台和后台通知。