Hi, in this blog post, you will learn everything about Firebase Push Notifications for the Web using JavaScript and PHP. You will learn how to send messages to users even when your website is not open. The browser will handle showing notifications when the user is connected to the internet.

Create a Firebase project

Here are the steps to create a Firebase project.

  1. Open console of the firebase.
  2. Click on Add project.
  3. Give a unique name to your project and click continue.
  4. If not needed, disable Google Analytics. Otherwise, you need to select a Google Analytics Account.
  5. Click Create project.
  6. After your project is created, click continue. Now your project screen will open.
  7. Click on ⚙ icon at the top of the left menu and click on the Project settings.
  8. Scroll down to the bottom of the page, and you will see that there are no apps in your project.
  9. Click on the </> icon to create a web app.
  10. Give your app a name. Don't check on the next checkbox as we don't need hosting for push notifications.
  11. Click the Register app and then click the Continue to Console button. Again scroll down, and this time you can see your app is added to your Firebase project.
  12. Here, you can see an object "firebaseConfig" with some credentials. This object will use in your code to access Firebase applications.

Further Firebase process for Push Notifications

There are some more things we need to do in our Firebase project that is specialized for push notifications only.

  1. Click on the Cloud Messaging tab, scroll down to the bottom, and click Generate Key Pair. This key will use on the client side for notifications.
  2. Click on the Service Accounts tab, scroll down to the bottom, and click Generate New Private Key. After a security warning, a JSON file will be downloaded. This file will use on the server side to send notifications. Don't rename the JSON file, use it as it is to make it difficult for others to access your file.

Let's code our Web App

There are two ways to use Firebase push notifications on the website. We will discuss both.

  1. Using Firebase Messaging service as a backend to send messages
  2. Using a custom PHP backend to send messages (Recommended)
1- Receive messages from the Firebase Messaging service

For using the first method, we just need to create an HTML file as the notification receiver and a service worker file as a background receiver. Let's create it.

In HTML, we need some UI to get messages when the app is opened and focused. Be sure, when a message receives inside the app, will not show as a notification in the background.

Add the given below CDN in your HTML file.

Get the firebaseConfig object from the Firebase project with all the credentials to initialize the Firebase app in the website using Firebase SDK. Get the Messaging instance from the app using `firebase.messaging()`. This instance will use for getting tokens and receiving messages. Now first use the `getToken()` method to get a token that is unique for each device. If we are sending notifications from the Firebase, we don't need that token and we don't save it. This token is automatically used by Firebase to send notifications.

Now, use `messaging.onMessage()` method to get the message when the app is open. We need to pass a callback function that will automatically trigger when data is received. You can use this JSON data however you want. I am displaying that data on the web page.

Create a JavaScript file and the file name should be `firebase-messaging-sw.js`. This should be in the root folder of the project. If you are using localhost then place the file in `htdocs` folder.

Add Firebase SDK CDN in the JS file as given below.

Use the same process to create messaging instance.

Try sending messages from Firebase

Open your Firebase project screen, and click on the All Products button in the left menu at the bottom. Under the build, you will find Cloud Messaging card, click on that. Messaging page will open. Click the New Campaign button and then click on the Notifications button from the popup. Give notification title and text and click Next. Select your app and click Next. Select Scheduling Now and click Review and then click Publish. Your Campaign will start. Where the previously created website is opened once, Firebase will send this notification to all of them. This may take 4 to 5 minutes to receive your notification. Your notification will not deliver until your browser, where the website was opened once, will be opened.

2- Receive messages from custom PHP backend

For receiving messages from our custom backend, we need to use the Device token of each device to send for sending notifications. Here, we will modify the `getToken()` method to get the device token.

When the Promise resolves successfully in the `getToken()` method, it gives a token. You can collect the token in the database for further use. I am just displaying tokens on the web page and using them directly for testing purposes.

Here, I have made a function `sendTokenToServer()` that can be used to send tokens to the server for storing purposes. It first checks from the local storage whether that is token has already sent or not using `isTokenSentToServer()` function. On successfully sending the token to the server, you can run the `setTokenSentToServer()` with the true parameter, which sent the local storage that the token has sent.

We also need to add an extra function in `firebase-messaging-sw.js for getting this type of notification. We will use `messaging.onBackgroundMessage()` method that will give payload in the callback function. Then you can use that data in `self.registration.showNotification()` function to show a notification.

This data will show on the web page if the website is open and focused as in the previous method using `messaging.onMessage()` method. But `keep in mind`, here, data have different keys, and make sure to check both before use.

Data received on the webpage using the first method:

firebase data display in console

Data received on the webpage using the second method:

firebase data display in console

Till here, we have completed our notification receiving process and next, we will code for sending notifications in PHP.

Try sending messages from custom PHP backend

Here we need to use the Google API library for PHP. Download it using composer (A PHP package manager) using the `composer require google/apiclient:^2.12.1` command. This library is used for getting access token from JSON file credentials. If you didn't download the JSON file from the Service Accounts tab, download it. We will use it here.

A file given with the source code `get_access_token.php` is used to create an access token using the JSON file and apiclient library.

Create a PHP file `send.php`, and include the `get_access_token.php` file. Now, we can use the `get_access_token()` function from that file. We need to pass the path of the JSON file as a parameter in this function.

Create an array of the stored device token, the token that is generated on the client side using the `getToken()` method. Each token represents a device for notifications. Loop through the array and run the `sendFCMNotification()` function for each token. This function takes our notification data and sends a notification to each device using a device token.

This function makes a post request to an endpoint. You need to add your project id in the endpoint URL.

Also, in this function, we can set the notification data. Below sample data is added. You can modify this according to your need.

Now, set post-request options. Here, our access token will use, and our notification data will be added.

Make a request using that options. On successful request, a notification will be shown on the devices whose device tokens are used.

Final Thoughts

You've now unlocked the potential of Firebase Push Notifications using JavaScript and PHP in your web app. With this integration, you can deliver personalized, real-time notifications that keep your users engaged and return them back for more. As you continue to explore the possibilities of Firebase, remember to abide by best practices and iterate on your notification strategy for optimal results. May your web app's notifications shine and elevate the user experience to new heights. Happy coding!