DEV Community

Cover image for How to Implement Push Notifications with Firebase Cloud Messaging (FCM) in Angular
Soham Galande
Soham Galande

Posted on

How to Implement Push Notifications with Firebase Cloud Messaging (FCM) in Angular

Push notifications are a powerful way to keep users engaged by delivering real-time updates directly to their devices. In this blog, I'll guide you through the process of implementing push notifications using Firebase Cloud Messaging (FCM) in an Angular application.

Why Firebase Cloud Messaging (FCM)?
Firebase Cloud Messaging (FCM) is a reliable, cross-platform messaging solution that allows you to send notifications for free. It supports various platforms, making it a versatile choice for web and mobile applications.

Step 1: Set Up Firebase in Your Project

Before diving into Angular-specific code, you need to set up Firebase.

  1. Create a Firebase Project:
  • Go to the Firebase Console.
  • Click on “Add Project” and complete the setup process.

2.Add Your Web App:

  • Once your project is created, add a new web app in the Firebase Console.
  • After adding the app, you’ll get a Firebase configuration object containing the necessary details like apiKey, authDomain, etc. You'll use this in your Angular app.

3.Enable Cloud Messaging:

  • Navigate to "Cloud Messaging" in the Firebase Console and ensure it’s enabled for your project.

Step 2: Set Up Angular Project

If you don’t have an Angular project set up yet, you can create one using Angular CLI.

  1. Create a New Angular Project:
ng new angular-fcm-demo
cd angular-fcm-demo
Enter fullscreen mode Exit fullscreen mode

2.Install Firebase and AngularFire:

To integrate Firebase with Angular, install the required packages:

npm install firebase @angular/fire --save
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Firebase in Angular

Add Firebase configuration to your Angular project.

  1. Update environment.ts:
  • Open the src/environments/environment.ts file and add your Firebase configuration:
export const environment = {
  production: false,
  firebase: {
    apiKey: "your-api-key",
    authDomain: "your-app.firebaseapp.com",
    projectId: "your-project-id",
    storageBucket: "your-project-id.appspot.com",
    messagingSenderId: "your-sender-id",
    appId: "your-app-id"
  }
};

Enter fullscreen mode Exit fullscreen mode

2.Initialize Firebase in app.module.ts:

  • Import and initialize Firebase in your Angular module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFireModule } from '@angular/fire';
import { AngularFireMessagingModule } from '@angular/fire/messaging';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireMessagingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Enter fullscreen mode Exit fullscreen mode

Step 4: Implement Push Notification Logic

Now that Firebase is set up, let's implement the logic for handling push notifications in your Angular app.

  1. Request Notification Permission:
  • In your app.component.ts or a dedicated service, request permission to show notifications:
import { Component, OnInit } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { mergeMapTo } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private afMessaging: AngularFireMessaging) {}

  ngOnInit(): void {
    this.requestPermission();
    this.listenForMessages();
  }

  requestPermission() {
    this.afMessaging.requestToken
      .subscribe(
        (token) => {
          console.log('Permission granted! Save to server!', token);
        },
        (error) => {
          console.error('Permission denied', error);
        }
      );
  }

  listenForMessages() {
    this.afMessaging.messages
      .subscribe((message) => {
        console.log('New message received. ', message);
      });
  }
}

Enter fullscreen mode Exit fullscreen mode

2.Handle Incoming Notifications:

  • To display notifications when your app is in the foreground, you may want to handle messages explicitly within your Angular components or services.

Step 5: Testing Your Setup

After implementing the logic, it's crucial to test your setup to ensure notifications are being sent and received correctly.

  1. Send a Test Notification:
  • You can send a test notification using the Firebase Console:

    Go to the “Cloud Messaging” section in your Firebase project.

    Enter the message details and target your app.

    Click “Send Test Message” and enter a valid device token.

2.Verify Notification on Device:

  • Ensure that your device receives the notification, and check the logs to confirm the successful delivery.

Challenges and Best Practices

Implementing push notifications can come with its challenges, especially when dealing with different behaviors across browsers or platforms. Here are some best practices:

  • Token Management: Securely manage and store device tokens on your backend.
  • User Segmentation: Target specific user segments with relevant content to increase engagement.
  • Retry Logic: Implement retry mechanisms to handle network failures or temporary issues in sending notifications.

Conclusion

Firebase Cloud Messaging (FCM) is a versatile tool for implementing push notifications in Angular applications. By following the steps outlined in this blog, you’ll be able to set up FCM, request user permissions, and handle incoming notifications in your Angular app. If you have any questions or experiences to share, feel free to leave a comment below!

Top comments (0)