Skip to contentSkip to navigationSkip to topbar
Rate this Page:

Web Push Quickstart: Firebase and Twilio Notify


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#(link takes you to an external page), Node.js(link takes you to an external page), PHP(link takes you to an external page), Python(link takes you to an external page), Ruby(link takes you to an external page), and Java(link takes you to an external page).

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

sign-up-for-or-sign-into-twilio page anchor

Before you can send push notifications with Notify and Firebase, you'll need to sign up for a Twilio account(link takes you to an external page) or sign into your existing account(link takes you to an external page).

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

create-a-project-on-google-firebase page anchor

If you haven't yet, sign up for Google's Firebase(link takes you to an external page). 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(link takes you to an external page):

Firebase-project-name-.

Find your Firebase secret key

find-your-firebase-secret-key page anchor

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-tab.

Save your Firebase key with Twilio

save-your-firebase-key-with-twilio page anchor

Once you have the secret, you need to create a credential on the Add a Push Credential(link takes you to an external page) 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:

notify-credential-web-push.

In the Notify console, create a new Notify service(link takes you to an external page). 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_service_configuration_webpush.

In order to authenticate your requests to Twilio API, you need to create a API Key(link takes you to an external page). 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(link takes you to an external page) 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).

twilio_new_api_key.

Gather your Twilio account information

gather-your-twilio-account-information page anchor

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 VALUEDESCRIPTION
Notify Service Instance SIDA service instance where all the data for our application is stored and scoped. You can create one in the console(link takes you to an external page).
Account SIDUsed to authenticate REST API requests - find it in the console here(link takes you to an external page).
API KeyUsed to authenticate REST API requests - SID (SKxxx..). It can be found here: https://www.twilio.com/console/runtime/api-keys/(link takes you to an external page)
API SecretUsed to authenticate REST API requests. Hopefully, you stored it, but if not create a new API Key here(link takes you to an external page).

Set up the backend server

set-up-the-backend-server page anchor

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:

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.

Follow the Node.js installation instructions here(link takes you to an external page) and complete the installation.

Download the Node.js server app and unzip it

download-the-nodejs-server-app-and-unzip-it page anchor

Download the Node.js server app(link takes you to an external page) and unzip it, or get it uncompressed from GitHub(link takes you to an external page)

Configure and run the server app on your machine

configure-and-run-the-server-app-on-your-machine page anchor

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 .

Notify Environment Configuration

notify-environment-configuration page anchor

Now we need to install our dependencies.

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


_10
npm install

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


_10
npm start

To confirm the server is running, visit http://localhost:3000(link takes you to an external page) in your web browser. You should see the home screen, informing you of which Twilio services you've configured.

Twilio SDK Starter Home Screen.

Set up the Twilio Notify sample Web Push Notification app

set-up-the-twilio-notify-sample-web-push-notification-app page anchor

Get the Twilio Notify sample Web Push app

get-the-twilio-notify-sample-web-push-app page anchor

To get you going quickly, we provide a Web Push sample app, available on GitHub(link takes you to an external page).

Configure Web Push Notifications

configure-web-push-notifications page anchor

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(link takes you to an external page) and open your Project Settings.

  • Navigate to General tab. From here, copy the Web API Key:
Firebase Settings General.
  • Navigate to Cloud Messaging tab and get the Sender ID :
Firebase Settings Cloud Messaging Sender Id.
  • Use the obtained keys to modify 2 files in the project

index.html:

Firebase Push Notifications

firebase-push-notifications page anchor

Use Notify and Firebase to create push notifications


_85
<html>
_85
<link rel="manifest" href="/manifest.json"/>
_85
_85
<head>
_85
<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js"></script>
_85
<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase-messaging.js"></script>
_85
<script src="notify_actions.js"></script>
_85
<title>Notify Firebase Cloud Notifications</title>
_85
</head>
_85
_85
<body>
_85
<h1>Quick Start Notify</h1>
_85
<a href="https://firebase.google.com/docs/cloud-messaging/js/client">More details how to set up Firebase web push</a>
_85
_85
<h2>Create Binding</h2>
_85
_85
<form id="binding_form">
_85
Identity: <input type="text" name="identity_field"><br>
_85
Address: <input type="text" name="address_field" size="200" value="<device token>"> <br>
_85
<input type="button" onclick="createBinding()" value="Create Binding">
_85
</form>
_85
_85
<script>
_85
// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client
_85
// Initialize Firebase
_85
var config = {
_85
apiKey: '<ENTER FIREBASE WEB API KEY HERE>',
_85
messagingSenderId: '<ENTER FIREBASE SENDER ID HERE>'
_85
};
_85
firebase.initializeApp(config);
_85
_85
// Retrieve Firebase Messaging object.
_85
const messaging = firebase.messaging();
_85
_85
messaging.requestPermission()
_85
.then(function() {
_85
console.log('Notification permission granted.');
_85
})
_85
.catch(function(err) {
_85
console.log('Unable to get permission to notify.', err);
_85
});
_85
_85
// Get Instance ID token. Initially, this makes a network call, once retrieved
_85
// subsequent calls to getToken will return from cache.
_85
messaging.getToken()
_85
.then(function(currentToken) {
_85
if (currentToken) {
_85
console.log('Token received: ', currentToken);
_85
document.forms["binding_form"]["address_field"].value = currentToken;
_85
} else {
_85
var errMsg = 'No Instance ID token available. Request permission to generate one.';
_85
alert(errMsg);
_85
document.forms["binding_form"]["address_field"].value = errMsg;
_85
}
_85
})
_85
.catch(function(err) {
_85
console.log('An error occurred while retrieving token. ', err);
_85
});
_85
_85
messaging.onMessage(function(payload) {
_85
console.log('Message received. ', payload);
_85
alert(payload.data.twi_body);
_85
});
_85
_85
function createBinding(){
_85
var identity = document.forms["binding_form"]["identity_field"].value;
_85
if (identity == "") {
_85
alert('Identity must be specified');
_85
return false;
_85
}
_85
_85
var address = document.forms["binding_form"]["address_field"].value;
_85
if (address == "") {
_85
alert('Address must be specified');
_85
return false;
_85
}
_85
_85
register(identity, address);
_85
}
_85
_85
</script>
_85
_85
</body>
_85
_85
</html>

firebase-messaging-sw.js:

Firebase Notify Integration

firebase-notify-integration page anchor

Initialize Firebase in JavaScript


_30
// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client
_30
// [START initialize_firebase_in_sw]
_30
// Give the service worker access to Firebase Messaging.
_30
// Note that you can only use Firebase Messaging here, other Firebase libraries
_30
// are not available in the service worker.
_30
importScripts('https://www.gstatic.com/firebasejs/4.8.0/firebase-app.js');
_30
importScripts('https://www.gstatic.com/firebasejs/4.8.0/firebase-messaging.js');
_30
_30
// Initialize the Firebase app in the service worker by passing in the
_30
// messagingSenderId.
_30
firebase.initializeApp({
_30
'messagingSenderId': '<ENTER FIREBASE SENDER ID HERE>'
_30
});
_30
_30
// Retrieve an instance of Firebase Messaging so that it can handle background
_30
// messages.
_30
const messaging = firebase.messaging();
_30
// [END initialize_firebase_in_sw]
_30
_30
messaging.setBackgroundMessageHandler(function(payload) {
_30
console.log('[firebase-messaging-sw.js] Received background message ', payload);
_30
// Customize notification here
_30
const notificationTitle = 'Background Message Title';
_30
const notificationOptions = {
_30
body: 'Background Message body.'
_30
};
_30
_30
return self.registration.showNotification(notificationTitle,
_30
notificationOptions);
_30
});

Create a Binding for Web Push Notifications (FCM)

create-a-binding-for-web-push-notifications-fcm page anchor

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(link takes you to an external page). 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.

Refresh (or open) the Web Push App at http://localhost:8000/(link takes you to an external page)

Notify Web Push Quickstart App Create Binding.

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.

(information)

Info

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)

Warning

Do not use Personally Identifiable Information for Identity

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:


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

Now that we have the Binding, we are ready to send a Push Notification.


Send a Push Notification to your App

send-a-push-notification-to-your-app page anchor

To send a notification, you can use the Notify page on the "backend" service you have running at http://localhost:3000(link takes you to an external page). 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 will send your device the message as a notification.

And that's all there is to it! You've now 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. We can't wait to see what you build - notify us when you've got something.


Rate this Page: