Back to Blog
Jul 29, 20265 min read21 views

Integrating Firebase Cloud Messaging (FCM) from Backend to Frontend in Next.js

Integration
JL
Written by Julius Legaspi
LinkedInGitHub
Share
Integrating Firebase Cloud Messaging (FCM) from Backend to Frontend in Next.js
# Integrating Firebase Cloud Messaging (FCM) from Backend to Frontend in Next.js

What is Firebase Cloud Messaging?

Firebase Cloud Messaging (FCM) is Google's free messaging service that allows you to send notifications to:

Web applications

Android apps

iOS apps

FCM handles message delivery, retries, and device management, making it one of the easiest ways to implement push notifications.

Typical use cases include:

Order updates

Chat messages

Marketing notifications

Task reminders

System alerts


Overall Architecture

Here's the complete flow of how push notifications work.

User Opens Website


Browser Requests Notification Permission


User Accepts


Firebase Generates FCM Token


Frontend Sends Token to Backend API


Backend Stores Token in Database


Business Event Happens
(Order, Message, etc.)


Backend Sends Notification Request


Firebase Cloud Messaging


Browser Receives Notification


User Clicks Notification

The frontend only registers the device and obtains a token. The backend is responsible for deciding when and what notifications to send.


Step 1: Configure Firebase

Create a Firebase project.

Inside the Firebase Console:

Create a project.

Enable Cloud Messaging.

Register a Web App.

Copy your Firebase configuration.

Example:

const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  messagingSenderId: "...",
  appId: "...",
};

Also generate a Web Push Certificate (VAPID Key) from the Cloud Messaging settings.

You'll need it when requesting the FCM token.


Step 2: Initialize Firebase on the Frontend

Create a Firebase client.

import { initializeApp } from "firebase/app";

const app = initializeApp(firebaseConfig);

Then initialize messaging.

import { getMessaging } from "firebase/messaging";

export const messaging = getMessaging(app);

Step 3: Ask User Permission

Browsers require users to grant notification permission.

const permission = await Notification.requestPermission();

if (permission === "granted") {
  console.log("Permission granted");
}

Without permission, FCM cannot send notifications.


Step 4: Get the FCM Token

Once permission is granted, request an FCM token.

const token = await getToken(messaging, {
    vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY
});

Example output:

eEdf98dfh8s9df89sdf89...

Think of this token as the unique address of a browser.

Every browser receives its own token.


Step 5: Send the Token to Your Backend

The frontend should immediately send the token to your API.

Example:

await fetch("/api/fcm/register", {
    method: "POST",
    body: JSON.stringify({
        token
    })
});

The backend now knows where notifications should be delivered.


Step 6: Store Tokens in Your Database

A typical table might look like this:

User ID

FCM Token

Created At

15

xY98df...

July 29

22

Ab98de...

July 29

If users log in from multiple browsers or devices, simply store multiple tokens for the same user.

Step 7: Trigger Notifications from the Backend

Whenever a business event occurs, your backend sends a request to Firebase.

Example events:

Someone sends a message

A payment succeeds

An order ships

An admin publishes an announcement

A task is assigned

Example payload:

{
  "message": {
    "token": "...",
    "notification": {
      "title": "New Message",
      "body": "You received a new message."
    }
  }
}

Firebase delivers the notification to the correct browser using the stored token.


Step 8: Handle Notifications on the Frontend

When the website is open, listen for incoming messages.

onMessage(messaging, (payload) => {
    console.log(payload);

    new Notification(payload.notification.title, {
        body: payload.notification.body,
    });
});

If the application is closed, the service worker handles background notifications automatically.


Backend Responsibilities

Your backend should:

Store FCM tokens

Associate tokens with users

Remove expired tokens

Trigger notifications based on business events

Log notification delivery if needed

The backend should never ask for browser permission—that's strictly a frontend responsibility.


Frontend Responsibilities

The frontend should:

Initialize Firebase

Request notification permission

Retrieve the FCM token

Send the token to the backend

Handle foreground notifications

Refresh tokens when necessary


Security Best Practices

To keep your notification system secure:

Never expose Firebase Admin SDK credentials to the client.

Authenticate API requests before saving FCM tokens.

Validate that the token belongs to the logged-in user.

Remove invalid or expired tokens returned by Firebase.

Use HTTPS in production, as browser push notifications require a secure context.


Common Issues

Notifications don't appear

Notification permission is blocked.

The service worker isn't registered.

The VAPID key is incorrect.

The FCM token has expired.

Token changes unexpectedly

Browsers may rotate tokens. Always update the backend whenever a new token is generated.

Duplicate notifications

This usually happens when the same token is stored multiple times. Store unique tokens and remove duplicates.


Conclusion

Firebase Cloud Messaging makes it straightforward to add real-time push notifications to your web application. The integration follows a simple workflow:

The frontend requests notification permission.

Firebase generates an FCM token.

The frontend sends the token to the backend.

The backend stores the token securely.

When a business event occurs, the backend sends a notification request to Firebase.

Firebase delivers the notification to the user's browser.

By clearly separating frontend and backend responsibilities, your application remains scalable, secure, and easier to maintain. Whether you're sending chat messages, order updates, or system alerts, FCM provides a reliable way to keep users informed in real time.

Comments (0)

Loading comments...