# Web Push Quickstart: Firebase and Twilio Notify

> \[!CAUTION]
>
> Twilio deprecated Notify in October 2022 and no longer supports it. Learn more about [transitioning off Notify](https://support.twilio.com/hc/en-us/articles/11746930233115-Transitioning-off-Notify).
>
> If you're starting a new project, use [Programmable Messaging](/docs/messaging) for SMS notifications. For push notifications, integrate directly with platform-specific services such as APNs for iOS or FCM for Android. If you've already built on Notify, visit the [transition guide](https://support.twilio.com/hc/en-us/articles/11746930233115-Transitioning-off-Notify) to learn about your options.

With just a few lines of code and a couple of API keys, your application can set up Push Notifications using Twilio Notify, Google Firebase and your choice of web language. We have code for you to stand up a server in [C#](https://github.com/TwilioDevEd/sdk-starter-csharp), [Node.js](https://github.com/TwilioDevEd/sdk-starter-node), [PHP](https://github.com/TwilioDevEd/sdk-starter-php), [Python](https://github.com/TwilioDevEd/sdk-starter-python), [Ruby](https://github.com/TwilioDevEd/sdk-starter-ruby), and [Java](https://github.com/TwilioDevEd/sdk-starter-java).

In this Quickstart, you will:

1. Sign up for Twilio Notify
2. Create a Google Firebase Project and create credentials
3. Set up Notify with your credentials
4. Set up a sample "backend" server
5. Run a toy "frontend" server
6. Configure push notifications
7. Run the app and test push notifications

## Sign up for or sign into Twilio

Before you can send push notifications with Notify and Firebase, you'll need to [sign up for a Twilio account](https://www.twilio.com/try-twilio) or [sign into your existing account](https://www.twilio.com/console).

For now, that's about it - you'll need to set up an account with Firebase and get FCM credentials before you can move forward with the app. Leave the Twilio tab open and move to the next step.

## Create a project on Google Firebase

If you haven't yet, [sign up for Google's Firebase](https://console.firebase.google.com/). We'll be using it as the base for our notification today. To use push notifications for your web apps, create a project on the [Firebase Console](https://console.firebase.google.com/):

![Prompt to enter a project name with example 'my-awesome-project-id'.](https://docs-resources.prod.twilio.com/1afaeb739e4bd061944ab3c5b51e03c15b4ce5f02b33ac7f0032b4c22a8da0be.jpg)

### Find your Firebase secret key

In Firebase, the FCM Secret is called the `Server Key` and you can find it in your Firebase console under your **Project Settings** and **Cloud Messaging** tab.

![Firebase Cloud Messaging settings highlighting Sender ID field.](https://docs-resources.prod.twilio.com/9d29e8a53ef2d185eb7fb1ec111da2a6cbed2fe28142cdb4b75844964bc94bd3.png)

### Save your Firebase key with Twilio

Once you have the secret, you need to create a credential on the [Add a Push Credential](https://www.twilio.com/console/notify/credentials/create) page on the Twilio Console using the FCM Secret.

Give it a memorable name and paste the FCM Server Key into the *"FCM Push Credentials"* text box:

![Form to create a new credential with fields for friendly name, type, and FCM secret.](https://docs-resources.prod.twilio.com/43ddef7b5ae726ed1700de9f2642a63253ee71c8ce4d343cc24f180bee803d81.png)

## Configure Notify

[In the Notify console, create a new Notify service](https://www.twilio.com/console/notify/services). Inside the new service in the **FCM Credential SID** dropdown, select the **Credential** that you have just created.

Make a note of the Service SID. You will use it later when you start writing code.

![Notify Push Web QuickStart configuration with FCM Credential SID set to Notify Web Push Secret.](https://docs-resources.prod.twilio.com/ae1098dbe8e1f7dbe945a51afb6cf76ab6a08b16f3f834946f8b9440e37affe6.png)

### Create Twilio API Keys

In order to authenticate your requests to Twilio API, you need to create a [API Key](https://www.twilio.com/console/runtime/api-keys). If you have already been using Twilio and have created API Keys, you can skip this step.

In Console, go to [https://www.twilio.com/console/runtime/api-keys](https://www.twilio.com/console/runtime/api-keys) and click the **Create API Key** button to create a new API key. Give your new key a **Friendly Name** and choose the "**Standard**" type. Hit the "Create API Key" button to generate the key.

The generated Secret is shown only ***once***, store it in a secure place. You will not be able to see the secret in the Console later. (If you do miss it, you can generate a new service).

![Form to create a new Twilio API key with fields for friendly name, region, and key type.](https://docs-resources.prod.twilio.com/1dff1cd6dd9d31dca7216f80b76af2638aaa0571f52ed0346eb399438cba5488.png)

### Gather your Twilio account information

Next, we need to grab all the necessary information from our Twilio account. Here's a list of what we'll need to gather:

| **CONFIG VALUE**            | **DESCRIPTION**                                                                                                                                                                                           |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Notify Service Instance SID | A [service](/docs/notify/api/service-resource) instance where all the data for our application is stored and scoped. You can create one in the [console](https://www.twilio.com/console/notify/services). |
| Account SID                 | Used to authenticate REST API requests - [find it in the console here](https://www.twilio.com/user/account/settings).                                                                                     |
| API Key                     | Used to authenticate REST API requests - SID (SKxxx..). It can be found here: [https://www.twilio.com/console/runtime/api-keys/](https://www.twilio.com/console/runtime/api-keys/)                        |
| API Secret                  | Used to authenticate REST API requests. Hopefully, you stored it, but if not [create a new API Key here](https://www.twilio.com/console/runtime/api-keys/).                                               |

## Set up the backend server

When using the Notify service, you need to *register* devices to receive notifications and then *send* notifications to those devices. To get you going quickly, we've created backend servers for the following languages:

* [C#](https://github.com/TwilioDevEd/sdk-starter-csharp)
* [Node.js](https://github.com/TwilioDevEd/sdk-starter-node)
* [PHP](https://github.com/TwilioDevEd/sdk-starter-php)
* [Python](https://github.com/TwilioDevEd/sdk-starter-python)
* [Ruby](https://github.com/TwilioDevEd/sdk-starter-ruby)
* [Java](https://github.com/TwilioDevEd/sdk-starter-java)

The sample mobile app is set up to communicate with the server-side app to register a device for notifications.

For this example, we'll use the **Node.js** server. Feel free to copy our choice or follow along in the language you prefer.

### Install Node.js

Follow the Node.js installation instructions [here](https://nodejs.org/en/download/) and complete the installation.

### Download the Node.js server app and unzip it

[Download the Node.js server app](https://github.com/TwilioDevEd/sdk-starter-node/archive/master.zip) and unzip it, or get it uncompressed from [GitHub](https://github.com/TwilioDevEd/sdk-starter-node)

### Configure and run the server app on your machine

Now that you have Node.js installed and the Node.js server downloaded and unpacked, it is time to configure the server with your specific account information.

1. Copy the `.env.example` file to `.env`
2. Next, edit the `.env` file to include the four configuration parameters (**Account SID**, **API Key SID**, **API Key Secret**, **Notify Service SID**) we [gathered from above](/docs/notify/quickstart/android).

### Notify Environment Configuration

Now we need to install our dependencies.

In a Terminal window, navigate to the folder where you unzipped or downloaded the app and run:

```bash
npm install
```

Once we've done configuring we're ready to start the server - again in your terminal, run:

```bash
npm start
```

To confirm the server is running, visit `http://localhost:3000` in your web browser. You should see the home screen, informing you of which Twilio services you've configured.

![Twilio Server Starter Kit setup with account info and product configuration status.](https://docs-resources.prod.twilio.com/bdf405173767aab976d058ef20f2d3e829356406425980d2559851de132a17ab.png)

### Set up the Twilio Notify sample Web Push Notification app

#### Get the Twilio Notify sample Web Push app

To get you going quickly, we provide a Web Push sample app, available on [GitHub](https://github.com/TwilioDevEd/notify-quickstart-webpush).

#### Configure Web Push Notifications

The following steps will guide you to configure Web Push Notifications for the Twilio Notify sample Web Push app.

You'll need to collect the *Firebase Sender ID* and *Web API Key* and configure the demo app for your Firebase project. To obtain these keys, go to the [Firebase Console](https://console.firebase.google.com/) and open your **Project Settings**.

* Navigate to **General** tab. From here, copy the **Web API** Key:

![Firebase settings showing project name and Web API Key highlighted.](https://docs-resources.prod.twilio.com/ff7a07541c842454cf910bdc407d72fd7e7c51c01b369c5805035cb8a1f02e82.png)

* Navigate to **Cloud Messaging** tab and get the **Sender ID**:

![Firebase Settings Cloud Messaging Sender Id.](https://docs-resources.prod.twilio.com/1ba0fa3bb3387c9551af1a297f8c05b6fe92ca293e0cd1dddfa525af825dfc90.png)

* Use the obtained keys to modify 2 files in the project

**index.html:**

```html title="Firebase Push Notifications" description="Use Notify and Firebase to create push notifications"
<!-- !mark(25,26,27,28,29) -->
<html>
    <link rel="manifest" href="/manifest.json"/>

    <head>
        <script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-messaging.js"></script>
        <script src="notify_actions.js"></script>
        <title>Notify Firebase Cloud Notifications</title>
    </head>

    <body>
        <h1>Quick Start Notify</h1>
        <a href="https://firebase.google.com/docs/cloud-messaging/js/client">More details how to set up Firebase web push</a>

        <h2>Create Binding</h2>

        <form id="binding_form">
        Identity: <input type="text" name="identity_field"><br>
        Address: <input type="text" name="address_field" size="200" value="<device token>"> <br>
        <input type="button" onclick="createBinding()" value="Create Binding">
        </form>

        <script>
            // firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client
            // Initialize Firebase
            var config = {
                apiKey: '<ENTER FIREBASE WEB API KEY HERE>',
                messagingSenderId: '<ENTER FIREBASE SENDER ID HERE>'
            };
            firebase.initializeApp(config);

            // Retrieve Firebase Messaging object.
            const messaging = firebase.messaging();

            messaging.requestPermission()
                    .then(function() {
                        console.log('Notification permission granted.');
                    })
                    .catch(function(err) {
                        console.log('Unable to get permission to notify.', err);
                    });

            // Get Instance ID token. Initially, this makes a network call, once retrieved
            // subsequent calls to getToken will return from cache.
            messaging.getToken()
                    .then(function(currentToken) {
                        if (currentToken) {
                            console.log('Token received: ', currentToken);
                            document.forms["binding_form"]["address_field"].value = currentToken;
                        } else {
                            var errMsg = 'No Instance ID token available. Request permission to generate one.';
                            alert(errMsg);
                            document.forms["binding_form"]["address_field"].value = errMsg;
                        }
                    })
                    .catch(function(err) {
                        console.log('An error occurred while retrieving token. ', err);
                    });

            messaging.onMessage(function(payload) {
                console.log('Message received. ', payload);
                alert(payload.data.twi_body);
            });

            function createBinding(){
                var identity = document.forms["binding_form"]["identity_field"].value;
                if (identity == "") {
                    alert('Identity must be specified');
                    return false;
                }

                var address = document.forms["binding_form"]["address_field"].value;
                if (address == "") {
                    alert('Address must be specified');
                    return false;
                }

                register(identity, address);
            }

        </script>

    </body>

</html>
```

**firebase-messaging-sw.js:**

```js title="Firebase Notify Integration" description="Initialize Firebase in JavaScript"
// !mark(10,11,12,13,9)
// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client
// [START initialize_firebase_in_sw]
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.0/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
    'messagingSenderId': '<ENTER FIREBASE SENDER ID HERE>'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// [END initialize_firebase_in_sw]

messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
        body: 'Background Message body.'
    };

    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});

```

### Create a Binding for Web Push Notifications (FCM)

Next, we need to create a binding between an `Identity` and the browser using the web app. The `Identity` can be any unique identifier you choose, for example, a [GUID](https://en.wikipedia.org/wiki/Universally_unique_identifier). In this quickstart, we take care of that with the web push app. For more about *Identity* and *Bindings* visit the [Binding resource reference API](/docs/notify/api/binding-resource).

Refresh (or open) the Web Push App at `http://localhost:8000`.

![Web page showing Quick Start Notify with fields for Identity and Address to create binding.](https://docs-resources.prod.twilio.com/4be85647f2c9c1a6d919dc45c03284141b7c02f0310299f8c38cd24f32d95a15.png)

If you are running the sample app in debugger mode and it wasn't successful, you'll see an error message printed in the console.

> \[!NOTE]
>
> **Note**: If you do not see a device token in the Address bar the first time you launch the app, reload the page. The demo app code is naive and doesn't handle the race between the App asking for and obtaining a token. Additionally, check the browser console for misconfiguration issues or hints.

> \[!WARNING]
>
> Notify uses Identity as the unique identifier of a user. Do not use directly identifying information (*personally identifiable information* or *PII*) such as a person's name, home address, email address, phone number, et cetera, as the `Identity`. The system that will process this attribute assumes it is not directly identifying information.

In the app enter the `Identity` you chose and click the button "Create Binding".

This action creates a *Binding* which uniquely identifies a user on a certain device running your application.

In the terminal window running the "backend" (Node.js) server, you should see something like this:

```bash
BindingInstance {
  _version:
   V1 {
     _domain:
      Notify {
        twilio: [Object],
        baseUrl: 'https://notify.twilio.com',
        _v1: [Circular] },
     _version: 'v1',
     _credentials: undefined,
     _services:
      { [Function: ServiceListInstance]
        _version: [Circular],
        _solution: {},
        _uri: '/Services',
        create: [Function: create],
        each: [Function: each],
        list: [Function: list],
        page: [Function: page],
        get: [Function: get] } },
  sid: 'BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  accountSid: 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
  serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
  dateCreated: 2017-01-17T13:07:39.000Z,
  dateUpdated: 2017-01-17T13:07:39.000Z,
  notificationProtocolVersion: '3',
  endpoint: 'user9999999XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  identity: 'Bob Builder',
  bindingType: 'fcm',
  address: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  tags: [],
  url: 'https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Bindings/BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  _context: undefined,
  _solution:
   { serviceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
     sid: 'BSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' } }

```

As you have the *Binding*, you're ready to send a Push Notification.

## Send a Push Notification to your App

To send a notification, you can use the Notify page on the "backend" service you have running at `http://localhost:3000`. Go ahead and click the "Notify" button at the bottom of the home page to go to the Notify page.

On this page, send a message to the identity you used in the app. Because you registered a binding with Twilio, the server sends your device the message as a notification.

You've got a "frontend" and a "backend" app which can send push notifications using Notify and Firebase, and you're ready to go off and build your own application. Let's build something amazing — notify us when you've got something.
