Push Notifications on the Web for Conversations (classic)
(error)
Programmable Chat deprecated
Programmable Chat has been deprecated and receives no support. Twilio has turned its focus to the next generation of chat: Twilio Conversations. Find out more about the EOL process.
- To start a project, see Conversations.
- To switch from Programmable Chat, see the Migration Guide to learn about how to switch.
Push notifications are an important part of the web experience. Users have grown accustomed to push notifications being part of virtually every app that they use. The Twilio Conversations (classic) JavaScript SDK can integrate Firebase Cloud Messaging (FCM) for push notifications. All examples follow Firebase v9 or later.
You must manage your push credentials. To send any notifications through FCM, the Conversations (classic) SDK requires your registration token. Let's go through the process of managing your push credentials.
- Turn on push notifications for your Service instance.
- Complete the Add Firebase to your JavaScript project guide through the Firebase Console.
- The Add Firebase SDK step in the Add Firebase to your web app page includes the needed code for Firebase integration. Click the Copy button for that code and paste it into a text document for later use.
- Go to the Cloud Messaging settings in your Firebase Project.
- Scroll to Web configuration.
- Press Generate key pair.
- Copy the displayed public key and paste it into a text document for later use. This key is also known as the Voluntary Application Server Identification for Web Push (VAPID) key.
- Create a Credential resource in the Twilio Console.
- Type the human-readable name for this credential in the Friendly Name box.
- Choose FCM Push Credentials from the Type dropdown menu. To generate a credential SID using your API key, see the Credentials page in the legacy console page.
- Click Create.
- In your terminal, set all of your credentials as environment variables. This follows security best practices.
1export TWILIO_ACCOUNT_SID="{my_account_sid}"2export TWILIO_API_KEY="{my_api_key}"3export TWILIO_API_SECRET="{my_api_secret}"4export TWILIO_CONVERSATIONS_SERVICE_SID="{my_conversations_service_sid}"5export TWILIO_FCM_CREDENTIAL_SID="{my_fcm_credential_sid}"6export FIREBASE_API_KEY="{my_firebase_api_key}"7export FIREBASE_AUTH_DOMAIN="{my_firebase_auth_domain}"8export FIREBASE_PROJECT_ID="{my_firebase_project_id}"9export FIREBASE_STORAGE_BUCKET="{my_firebase_storage_bucket}"10export FIREBASE_MESSAGING_SENDER_ID="{my_firebase_messaging_sender_id}"11export FIREBASE_APP_ID="{my_firebase_app_id}"12export FIREBASE_VAPID="{my_firebase_vapid}"
- Open your app code file.
- In your app code, declare and import your functions.
1// Import the necessary functions from the modern Firebase SDKs2import { initializeApp } from "firebase/app";3import { getMessaging, getToken, onMessage } from "firebase/messaging";4import twilio from "twilio";
- Add your credentials.
1// Twilio Configuration Variables2const accountSid = process.env.TWILIO_ACCOUNT_SID;3const apiKey = process.env.TWILIO_API_KEY;4const apiSecret = process.env.TWILIO_API_SECRET;5const conversationServiceSid = process.env.TWILIO_CONVERSATIONS_SERVICE_SID;6const fcmCredentialSid = process.env.TWILIO_FCM_CREDENTIAL_SID;7// Firebase Configuration Variables8const firebaseApiKey = process.env.FIREBASE_API_KEY;9const firebaseAuthDomain = process.env.FIREBASE_AUTH_DOMAIN;10const firebaseProjectId = process.env.FIREBASE_PROJECT_ID;11const firebaseStorageBucket = process.env.FIREBASE_STORAGE_BUCKET;12const firebaseMessagingSenderId = process.env.FIREBASE_MESSAGING_SENDER_ID;13const firebaseAppId = process.env.FIREBASE_APP_ID;14const firebaseVapid = process.env.FIREBASE_VAPID;
- Initialize your Firebase Configuration.
1// Firebase Configuration2const firebaseConfig = {3apiKey: firebaseApiKey,4authDomain: firebaseAuthDomain,5projectId: firebaseProjectId,6storageBucket: firebaseStorageBucket,7messagingSenderId: firebaseMessagingSenderId,8appId: firebaseAppId9};
- Initialize your Twilio chat grant.
1const AccessToken = twilio.jwt.AccessToken;2const ChatGrant = AccessToken.ChatGrant;34const chatGrant = new ChatGrant({5serviceSid: conversationServiceSid,6// Passing the environment variable string directly per SDK requirements7pushCredentialSid: fcmCredentialSid8});
- Initialize Firebase in your web app
1const app = firebaseAppModule.initializeApp(firebaseConfig);2const messaging = firebaseMessagingModule.getMessaging(app);34console.log("✅ Firebase libraries verified and initialized successfully.");
- Request push permissions from the end user and get your FCM token.
1async function initializeAppWithPush() {2try {3console.log("Checking and importing Firebase libraries...");45// Dynamically attempt to load the modules to verify they exist6const firebaseAppModule = await import("firebase/app");7const firebaseMessagingModule = await import("firebase/messaging");89// Guard Clause: Verify necessary initialization functions are present10if (typeof firebaseAppModule.initializeApp !== "function" ||11typeof firebaseMessagingModule.getMessaging !== "function") {12throw new Error("Required Firebase initialization functions are missing from the loaded modules.");13}1415// Initialize Firebase Core and Messaging16const app = firebaseAppModule.initializeApp(firebaseConfig);17const messaging = firebaseMessagingModule.getMessaging(app);1819console.log("✅ Firebase libraries verified and initialized successfully.");2021// --- PERMISSION AND TOKEN MANAGEMENT ---2223// Request permission using native browser API24const permission = await Notification.requestPermission();2526if (permission !== 'granted') {27throw new Error("Notification permission was denied by the user.");28}2930console.log("Notification permission granted.");3132// Retrieve FCM Token using modern modular function pattern33// Note: process.env.FIREBASE_VAPID_KEY is recommended for modern web pushes34const fcmToken = await firebaseMessagingModule.getToken(messaging, {35vapidKey: process.env.FIREBASE_VAPID_KEY36});3738console.log("FCM Token retrieved successfully.");3940// --- CONTINUING WITH STEP 7: TWILIO INTEGRATION ---4142// Passing FCM token to the conversationClientInstance to register for push notifications43conversationClientInstance.setPushRegistrationId('fcm', fcmToken);4445// Registering event listener on new message from Firebase to pass to Twilio Conversations SDK46firebaseMessagingModule.onMessage(messaging, (payload) => {47conversationClientInstance.handlePushNotification(payload);48});4950console.log("✅ Push registration and event listeners successfully attached.");5152} catch (err) {53// Gracefully handles missing libraries, denied permissions, or missing tokens in one block54console.error("❌ CRITICAL ERROR: Application execution halted.");55console.error(`Details: ${err.message}`);5657// Stop further processing completely58return;59}60}
- Add the function call to run the script.
1// Run the script2initializeAppWithPush();