Push Notification using Firebase in a Vue Application

Posted by


Vue.js is a popular JavaScript framework for building user interfaces and single-page applications. Firebase is a mobile and web application development platform that provides tools and services for app development. In this tutorial, we will learn how to send push notifications to a Vue.js application using Firebase Cloud Messaging (FCM).

  1. Set up Firebase project:

First, you need to create a Firebase project. Go to the Firebase console (https://console.firebase.google.com/) and create a new project. Once the project is created, you will be redirected to the project dashboard.

Next, click on the "Project settings" icon in the top right corner of the dashboard. Go to the "Cloud Messaging" tab and copy the "Server key" and "Sender ID". We will need these values later in the tutorial.

  1. Install Firebase SDK:

To send push notifications using Firebase Cloud Messaging in Vue.js, we need to install the Firebase SDK. You can install the Firebase SDK by including the following script tag in the head section of your HTML file:

<script src="https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.0/firebase-messaging.js"></script>

Alternatively, you can install the Firebase SDK using npm:

npm install firebase@9.6.0 --save
  1. Initialize Firebase in your Vue.js application:

In your main.js file, initialize Firebase with your Firebase project configuration. Replace the configuration values with your Firebase project’s configuration values.

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

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging();
  1. Request permission to send push notifications:

To send push notifications to the user’s device, you need to request permission to send notifications. Add the following code to request permission to send notifications when the Vue component is mounted.

import { onMounted } from 'vue';

onMounted(() => {
  Notification.requestPermission().then((permission) => {
    if (permission === 'granted') {
      console.log('Permission granted');
    }
  });
});
  1. Handle incoming push notifications:

To handle incoming push notifications, add the following code to your main.js file. This code listens for incoming push notifications and displays an alert when a notification is received.

import { onMessage } from 'firebase/messaging';

onMessage(messaging, (payload) => {
  alert(payload.notification.body);
});
  1. Send push notifications using Firebase:

To send push notifications using Firebase, you can use the Firebase Cloud Messaging API. You can send push notifications to a specific device or to all devices that have installed your Vue.js application.

Here’s an example of how to send a push notification to a specific device using the Firebase Cloud Messaging API:

const message = {
  token: 'DEVICE_TOKEN',
  notification: {
    title: 'Hello',
    body: 'This is a notification from Firebase',
  },
};

messaging.send(message).then((response) => {
  console.log('Notification sent successfully:', response);
}).catch((error) => {
  console.error('Error sending notification:', error);
});

Replace ‘DEVICE_TOKEN’ with the device token of the device you want to send the push notification to. You can obtain the device token by registering the device with Firebase Cloud Messaging.

Congratulations! You have successfully set up push notifications in your Vue.js application using Firebase Cloud Messaging. You can now send push notifications to your users’ devices using the Firebase Cloud Messaging API.

0 0 votes
Article Rating
23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@leviomagbemi
2 months ago

Thank you so much!

@kennyjeancarloarevaloreyes6976
2 months ago

The notifications in the foreground and according to the plan only reach me through the console, everything is fine, but the notification window is not shown and when I close the page the sale does not appear, what is the reason?

@tyresewatchthis8025
2 months ago

Bro you have no idea how much you helped me. Thanks a lot, I subscribed, please make more Vue.js + Firebase videos

@ablegreimerguzmanperez7250
2 months ago

Salvaste mi vida, mi carrera universitaria, todo viejo… MUCHAS GRACIAS!!!

@chill-hot-stream
2 months ago

nice tutorial it helped me today with nuxt3 integration

@tiagofarias-ti
2 months ago

Perfect

@gapboi6044
2 months ago

Thank you so much! I've watched many videos and could not understand how to do this with firebase's docs

@Mewain
2 months ago

The notification doesn't seems to be received on ios. (standalone/fullscreen mode)
Do you know why ?

@Mewain
2 months ago

You are the boss ! thank you

@moali6657
2 months ago

hi
is it safe to put the file in public where the file has the FCM keys?

@hungha9991
2 months ago

Hi, thank for your share – thank you very much, i did it, but i have one question, if i standing at localhost web then send noti, i cant get noti instead firebase-admin already push, buts if i go to other url then i get noti, Did i do something wrong ? Many thank you

@PkStarstormAlfa
2 months ago

background notifications aren't showing up, I get the console log when I focus the page, but no notification popup

@kaliloteixeira2089
2 months ago

Does it works in PWA's? Using VUE 2.

@hieuNguyen-om8sg
2 months ago

thank you so much for the guide, i got it to work the same as you at 9:15 but my project uses laravel as back-end so is there a code or place you know that i can read up on how to set up on that side ? im using axios to connect between the two, the firebase setting does not have code for php it would seems

@MarcosGrandesso
2 months ago

awesome thanks <3

@bryancan
2 months ago

This is great, thanks. Now what if I want to use Capacitor to turn this Vue.js app into an ios/android mobile app?
Will it just work, or is there an entirely different process?

@user-lc5xi9zs7v
2 months ago

Thank you from here to sky

@MrBoXon
2 months ago

Thank you, finally managed to get this to work! Is there any way to toggle a "Heads up" notification on Android devices? I can see it in my notification center, but currently it doesnt generate a popup notification or show on lock screen. Any idea? 🙂

@yazidakbar5373
2 months ago

THANK YOUUUU LOVE YOU BROOOO 💥💥💥💥💥💥💥

@user-od2xf7ng7i
2 months ago

Thanks so much!