In this tutorial, we will cover how to send push notifications to an Oracle Visual Builder (VB) Progressive Web Application (PWA) using a Node.js server and Oracle API Gateway. Push notifications are an essential feature for engaging users, and integrating them into your PWA can significantly enhance the user experience.
This post will walk you through three key steps:
- Setting up Node.js for Push Notifications
- Creating an API Gateway for Communication
- Configuring Push Notifications in Visual Builder
Let’s dive into each of these steps with code snippets and explanations to help you implement push notifications seamlessly.
Part 1: Setting up Node.js for Push Notifications
The first step involves creating a Node.js server that will handle push notifications. The server will be responsible for managing notification requests and delivering them to the clients (your PWA users).
You can find the source code for the server here.
To get started:
- Create Compute VM.
- Clone the repository.
- Follow the instructions in the README file for setting up the server.
Part 2: Creating an API Gateway
Next, we will create an Oracle API Gateway that allows your VB app to communicate securely with your Node.js server. The API Gateway ensures that your app can call your server and handle notifications.
Steps:
- Navigate to the API Gateway Service: Create a new gateway.
- Define the API: Set up an API that routes to your Node.js server. Create an API endpoint that points to the
/sendNotificationroute of your server.- Route Path:
/save-subscription - Method:
POST - Backend Type:
HTTPwith the URL of your Node.js server.
- Route Path:
- Deploy the API: Once the API is created, deploy it and note down the endpoint URL. You will use this in the VB configuration.
Part 3: Configuring Push Notifications in VB
Now that we have the server and API Gateway set up, the next step is to configure the VB app to register service workers and receive push notifications.
sw.js file explanation:
This is what our sw.js file looks like:
urlBase64ToUint8Array(base64String)
- Converts a base64 encoded string (used for the VAPID public key) into a
Uint8Array. - The VAPID key is needed to authenticate the push subscription between the client and the push service.
saveSubscription(subscription)
- Sends the user's push subscription (the endpoint and keys generated by the browser) to your server using a
POSTrequest. - The server stores this subscription so it can later send push notifications to that specific user.
self.addEventListener("activate", async (e) => {...})
- This event listener is triggered when the service worker is activated.
- It creates a new push notification subscription using
pushManager.subscribe().userVisibleOnly: trueensures that the notifications are always shown to the user.- The
applicationServerKeyis the VAPID public key, required to secure the subscription.
- The subscription is then sent to the server via
saveSubscription().
self.addEventListener("push", event => {...})
- Triggered when a push notification is received from the server.
- It extracts the payload (the notification data) from the event.
- The notification is displayed using
self.registration.showNotification().
const urlBase64ToUint8Array = base64String => {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
};
const saveSubscription = async (subscription) => {
const response = await fetch('..../save-subscription', {
method: 'post',
headers: { 'Content-type': "application/json" },
body: JSON.stringify(subscription)
});
return response.json();
};
self.addEventListener("activate", async (e) => {
const subscription = await self.registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array("") // Public Vapid Key needs to be provided
});
const response = await saveSubscription(subscription);
});
self.addEventListener("push", event => {
const payload = event.data.json();
const customMessage = payload.body;
const options = { body: customMessage };
self.registration.showNotification("This is notification", options);
});
Registering the Service Worker in VB
To register this service worker, create a button in your VB app, and add the following JavaScript in the action chain:
define([], () => {
'use strict';
class PageModule { }
const checkPermission = () => {
if (!('serviceWorker' in navigator)) {
throw new Error("No support for service worker!");
}
if (!('Notification' in window)) {
throw new Error("No support for notification API");
}
if (!('PushManager' in window)) {
throw new Error("No support for Push API");
}
};
const registerSW = async (path) => {
let registration;
if ('serviceWorker' in navigator && 'PushManager' in window) {
registration = await navigator.serviceWorker.register(path + 'sw.js').then(serviceWorkerRegistration => {
console.info('Service worker was registered.');
console.info({ serviceWorkerRegistration });
}).catch(error => {
console.error('An error occurred while registering the service worker.');
console.error(error);
});
} else {
console.error('Browser does not support service workers or push messages.');
}
return registration;
};
const requestNotificationPermission = async () => {
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
throw new Error("Notification permission not granted");
}
};
PageModule.prototype.main = async (path) => {
checkPermission();
await requestNotificationPermission();
await registerSW(path);
};
return PageModule;
});
Explanation:
checkPermission(): Ensures the browser supports service workers, notifications, and push messages.registerSW(path): Registers the service worker located at the specified path.requestNotificationPermission(): Requests permission from the user to display notifications.main(): Coordinates the setup process, checking permissions, requesting notification access, and registering the service worker.
With this setup, your VB PWA can now receive push notifications from the Node.js server via the Oracle API Gateway!
Go through this video for more in depth step by step instruction on how to setup.
