The Firebase JS SDK is now in BETA!
This EAP site is no longer maintained. See the official Firebase Documentation site for the latest documentation and information about the Firebase JS SDK.

Messaging

Common use cases

Core

Initialization

import { getMessaging } from "firebase/messaging";

const messaging = getMessaging();

Request permission

Notification.requestPermission().then((permission) => {
  if (permission === 'granted') {
    console.log('Notification permission granted.');
    // TODO(developer): Retrieve a registration token for use with FCM.
    // ...
  } else {
    console.log('Unable to get permission to notify.');
  }
});

Get token

import { getMessaging, getToken } from "firebase/messaging";

// Get registration token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
const messaging = getMessaging();
getToken(messaging, { vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => {
  if (currentToken) {
    // Send the token to your server and update the UI if necessary
    // ...
  } else {
    // Show permission request UI
    console.log('No registration token available. Request permission to generate one.');
    // ...
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
  // ...
});

Receive messages

// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
//   `messaging.onBackgroundMessage` handler.
import { getMessaging, onMessage } from "firebase/messaging";

const messaging = getMessaging();
onMessage(messaging, (payload) => {
  console.log('Message received. ', payload);
  // ...
});

Delete token

import { getMessaging, deleteToken } from "firebase/messaging";

const messaging = getMessaging();
deleteToken(messaging).then(() => {
  console.log('Token deleted.');
  // ...
}).catch((err) => {
  console.log('Unable to delete token. ', err);
});

Service Worker

Initialization

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = 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 = getMessaging(firebaseApp);

Background messages (coming soon!)

// TODO(snippet): This snippet is not yet translated to the @exp SDK