Skip to content

Messaging (FCM)

firekitMessaging wraps Firebase Cloud Messaging (FCM). It is browser-only — all methods are silently ignored during SSR.

import { firekitMessaging } from 'svelte-firekit';
// Prompts the browser for notification permission and returns an FCM token
const token = await firekitMessaging.requestPermission('YOUR_VAPID_KEY');
if (token) {
// Send this token to your server to enable targeted push notifications
await saveTokenToServer(token);
}
PropertyTypeDescription
tokenstring | nullCurrent FCM registration token
permissionNotificationPermission'granted' | 'denied' | 'default'
supportedbooleanWhether 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}

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 needed
unsubscribe();

Background messages are handled by a service worker. Create public/firebase-messaging-sw.js:

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 }
);
});