Messaging (FCM)
firekitMessaging wraps Firebase Cloud Messaging (FCM). It is browser-only — all methods are silently ignored during SSR.
import { firekitMessaging } from 'svelte-firekit';Request permission and get a token
Section titled “Request permission and get a token”// Prompts the browser for notification permission and returns an FCM tokenconst token = await firekitMessaging.requestPermission('YOUR_VAPID_KEY');
if (token) { // Send this token to your server to enable targeted push notifications await saveTokenToServer(token);}Reactive state
Section titled “Reactive state”| Property | Type | Description |
|---|---|---|
token | string | null | Current FCM registration token |
permission | NotificationPermission | 'granted' | 'denied' | 'default' |
supported | boolean | Whether FCM is supported in this browser |
<script lang="ts"> import { firekitMessaging } from 'svelte-firekit';</script>
{#if !firekitMessaging.supported} <p>Push notifications are not supported in this browser.</p>{:else if firekitMessaging.permission === 'denied'} <p>Notifications are blocked. Enable them in your browser settings.</p>{:else if firekitMessaging.permission === 'granted'} <p>Notifications enabled.</p>{:else} <button onclick={() => firekitMessaging.requestPermission('YOUR_VAPID_KEY')}> Enable notifications </button>{/if}Listen for foreground messages
Section titled “Listen for foreground messages”When your app is in the foreground, incoming messages are delivered to your onMessage handler rather than shown as browser notifications:
const unsubscribe = await firekitMessaging.onMessage((payload) => { console.log('Message received:', payload); console.log('Title:', payload.notification?.title); console.log('Body:', payload.notification?.body);
// Show a custom in-app notification showNotification(payload.notification?.title ?? 'New message');});
// Unsubscribe when no longer neededunsubscribe();Background messages (Service Worker)
Section titled “Background messages (Service Worker)”Background messages are handled by a service worker. Create public/firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/10.0.0/firebase-app-compat.js');importScripts('https://www.gstatic.com/firebasejs/10.0.0/firebase-messaging-compat.js');
firebase.initializeApp({ apiKey: '...', projectId: '...', messagingSenderId: '...', appId: '...',});
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => { self.registration.showNotification( payload.notification.title, { body: payload.notification.body } );});