Despite extensive hours scouring the internet for a user-friendly method to incorporate Firebase FCM Push Notification into my nuxt project, I came up empty-handed.
Despite extensive hours scouring the internet for a user-friendly method to incorporate Firebase FCM Push Notification into my nuxt project, I came up empty-handed.
Learn how to set up FCM Push Notifications for your NuxtJs/Vuejs project
Step 1
To begin, create your nuxt app using the command
npx create-nuxt-app <your-app-name>
Step 2
Next, install firebase by running npm install firebase
and @nuxt/firebase with npm install @nuxt/firebase
Step 3
Create your Firebase project by following these steps:
Access the Firebase console and create a new project https://i.sstatic.net/FGqRQ.png
Name your project https://i.sstatic.net/z9TLI.png
Optionally enable Google Analytics and click on create
https://i.sstatic.net/nBhnf.png
-Grab a cup of coffee while the project sets up ☕
https://i.sstatic.net/ujEtN.png
https://i.sstatic.net/WnzUh.png
Step 4
In your nuxt.config.js
, add the following configurations
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
'@nuxtjs/firebase',
],
// Firebase FCM setup
firebase: {
lazy: false,
config: {
apiKey: <apiKey>,
authDomain: <authDomain>,
projectId: <projectId>,
storageBucket: <storageBucket>,
messagingSenderId: <messagingSenderId>,
appId: <appId>,
measurementId: <measurementId>,
databaseURL: <databaseURL>,
},
onFirebaseHosting: false,
services: {
messaging: true,
}
},
messaging: {
createServiceWorker: true,
actions: [
{
action: 'goHome',
url: 'https://localhost:3000'
}
],
fcmPublicVapidKey: <vapidKey>
},
Obtain your vapidKey by navigating to Project Settings on the Firebase console and selecting Cloud Messaging. Generate the Key Pair and get your vapidKey as shown in the image below https://i.sstatic.net/y3zAU.png
Copy and paste this key into your nuxt.config.js
Step 5
In the static
folder at the root of your project, create a file named firebase-messaging-sw.js
. Insert the provided configs as demonstrated below
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing the generated config
var firebaseConfig = {
apiKey: <apiKey>,
authDomain: <authDomain>,
projectId: <projectId>,
storageBucket: <storageBucket>,
messagingSenderId: <messagingSenderId>,
appId: <appId>,
measurementId: <measurementId>,
databaseURL: <databaseURL>,
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
Step 6
Configure your index.vue as follows
<template>
<div>
<h1>Get Notified</h1>
</div>
</template>
<script>
export default {
data() {
return {
listenersStarted: false,
idToken: "",
};
},
mounted() {
this.startListeners();
},
methods: {
// FCM NOTIFICATION FUNCTIONS
async startListeners() {
await this.startOnMessageListener();
await this.startTokenRefreshListener();
await this.requestPermission();
await this.getIdToken();
this.listenersStarted = true;
},
startOnMessageListener() {
try {
this.$fire.messaging.onMessage((payload) => {
console.info("Message received : ", payload);
console.log(payload.notification.body);
});
} catch (e) {
console.error("Error : ", e);
}
},
startTokenRefreshListener() {
try {
this.$fire.messaging.onTokenRefresh(async () => {
try {
await this.$fire.messaging.getToken();
} catch (e) {
console.error("Error : ", e);
}
});
} catch (e) {
console.error("Error : ", e);
}
},
async requestPermission() {
try {
const permission = await Notification.requestPermission();
console.log("GIVEN notify perms");
console.log(permission);
} catch (e) {
console.error("Error : ", e);
}
},
async getIdToken() {
try {
this.idToken = await this.$fire.messaging.getToken();
console.log("TOKEN ID FOR this browser");
console.log(this.idToken);
} catch (e) {
console.error("Error : ", e);
}
},
},
};
</script>
Step 7
Run npm run dev
, check your console to see if notification display permissions have been granted. Allow notifications if prompted.
Step 8
Head over to Cloud Messaging on your Firebase dashboard under the Engage menu. Click on Send your first message
to compose the content of your notification and select your app as the target user. You should then receive a notification on your browser like shown in the image below
As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...
As a new React developer, I have a question about updating arrays with a form. Currently, I have the following arrays defined in my state: state = { loading: true, projects: [], tokens: [] , authors: [] , ...
Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...
My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...
I am attempting to create a sleek horizontal scroll bar within one of my div elements, similar to the example shown here: https://i.stack.imgur.com/ziWhi.png My project is based on the angular2 CLI. Progress so far: I came across this package angular2-s ...
When it comes to messaging via websockets between a HTML5 client and server running on node.js, I decided to use JSON as the message format. To streamline this process, I created common javascript code that defines different message content types and trans ...
In my current state, I have different dropdown options: this.state = { dropdown1: false, dropdown2: false, dropdown3: false } I am looking to access and update these dropdowns using this.setState, where the number after 'dropdown' is dy ...
Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...
Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...
As I dive into creating a socket-based application using Django-Channels, I've encountered an issue with connecting to the WebSocket. To demonstrate this problem, I set up a test project. The error message displayed in the JS Console: WebSocket con ...
I'm encountering an issue regarding my Alexa skill certification. Although I have passed all the requirements, I received feedback that includes the following points: Upon completing a task, the session remains open without any prompt to the user. It ...
Below is an HTML code snippet for checking for empty or null values in a text field: function myFormValidation() { alert("Hello"); var name = document.getElementById("name").value; alert(name); if (name == null || name == "") { document.ge ...
I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...
After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Partner</title> <!--styles for ...
Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...
Exploring the native async and await features in Node 7.6.0 has left me puzzled. I can't seem to figure out why my async call is just hanging instead of resolving. NLP module: const rest = require('unirest') const Redis = require('io ...
Is it possible to display a loader (gif) before the HTML is loaded and during a page transition? I have seen this type of effect on many websites and am curious if it can be implemented. If so, is it achievable using jQuery, AJAX, and PHP? I know how to ...
Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...
My HTML and PHP code consists of a select dropdown that looks like this: <select name="category" id="_category" class="_cateogry" onchange="submitTheForm() > option value="">Please select</option> <?php foreach ($categories as $cont ...