Progressive web apps (PWAs) allow brands to enjoy the advanced features of a mobile app without spending a lot of time developing it. With a PWA, you can deliver an app-like experience through a web browser, giving customers the sleek interface they expect while making the most of your development resources.
Like apps, PWAs can also send push notifications to give users timely information, regardless of their browser or device. These minimally intrusive notifications send updates directly to a user’s device to bring much-needed engagement to your PWA—without tricky workarounds, even when the app is not actively being viewed or is closed outside of the browser window.
Using push notifications in PWAs isn’t difficult, but setting things up still requires some technical know-how. Whether you’re a developer or a business owner, it’s important to understand how to leverage push notifications in a progressive web app. Implementing push notifications can significantly enhance communication and user engagement.
Setup generally requires a few steps:
- Know your requirements, including HTTPS hosting, service worker, and manifest file.
- Configure the service worker.
- Request user permissions.
- Integrate the push API.
- Send notifications from the server.
In this guide, we’ll translate the technical concepts behind using push notifications in PWAs. We’ll explain why they’re beneficial, share basic steps for setting them up, and offer five tips for leveraging the full benefits of push notifications in PWAs.
In this article:
- What Are Push Notifications in PWAs?
- Why Use Push Notifications for PWAs?
- Next.js Push Notification Setup
- 5 Tips for Leveraging the Full Potential of Push Notifications
- Witness the Magic of PWA Notifications Firsthand
- Frequently Asked Questions
Introduction to Progressive Web Apps
Progressive Web Apps (PWAs) are web applications that provide a native app-like experience to users. Built using web technologies such as HTML, CSS, and JavaScript, PWAs are designed to work seamlessly across multiple platforms, including desktop, mobile, and tablet devices. They offer a fast, engaging, and reliable user experience, similar to what users expect from native apps.
One of the standout features of PWAs is their ability to send push notifications. This capability allows developers to re-engage users by providing timely updates and information, even when the app is not actively in use. Push notifications can alert users to new content, special promotions, or important updates, ensuring that they stay connected with the app.
Progressive web apps have gained significant popularity in recent years, thanks to their ability to deliver an app-like experience without the need for users to download and install a separate application. They are supported by most modern browsers, including Chrome, Firefox, and Safari, making them a versatile and powerful tool for developers looking to create engaging web applications.
What Are Push Notifications in PWAs?
Photo by TippaPatt from Shutterstock
With PWA push notifications, your server sends push messages to a user’s device even when they aren’t actively using your web application. The alerts are displayed just like native app alerts but without the need to download yet another app to the user’s device.
This capability bridges the gap between web-based PWAs and native applications, giving you the power to engage users like you would with a native app.
PWAs use service workers to send push messages to users. These service workers are scripts that run in the background, separate from a webpage. The script allows you to send alerts without user interaction or a web page.
A service worker listens for a push event to manage incoming notifications from a push service, ensuring they are properly routed and displayed to users, even if the application is not actively running.
In other words, PWA push notifications synchronize data in the background, allowing you to send push notifications even if the user hasn’t opened the PWA in their browser.
The downside? With the introduction of the EU’s Digital Markets Act (DMA), Apple removed home screen web apps for iOS users in the EU. This was due to the DMA requiring home screen web apps to be allowed to use alternate web browsers, which Apple believed could allow malicious web apps to gain access to user’s devices.
Benefits of Push Notifications
Push notifications are a powerful tool for engaging users and driving conversions. They enable developers to send targeted, personalized messages to users, even when they are not actively using the app. This makes push notifications an effective way to notify users of new content, updates, or promotions, and to encourage them to return to the app.
By using push notifications, developers can significantly increase user engagement and build a loyal user base. These notifications can be customized to fit the specific needs of the app, ensuring that users receive relevant and timely information. Web push notifications are supported by most modern browsers, making it easy to implement them in progressive web apps.
Service workers play a crucial role in handling push notifications, ensuring that they are delivered even when the app is not open. Web push protocols also ensure secure data transmission, protecting user data during the notification process. Native mobile apps can also benefit from push notifications, and implementing them can be done using tools like Firebase Cloud Messaging or other push notification servers.
Overall, push notifications are an essential feature for any app looking to maintain a strong connection with its users, drive engagement, and provide a seamless user experience.
Why Use Push Notifications for PWAs?
Photo by Negative Space from Pexels
You went to the trouble of building a PWA; why not get more engagement for your trouble? Web push notifications boost user engagement and retention by communicating with them when they aren’t using your web app, maintaining a connection between the user and your company, especially for mobile users across various operating systems.
Push notifications are helpful for many reasons, but the most compelling benefits are:
- Timely messages: Immediately contact your users with time-sensitive announcements or offers. This is especially helpful for urgent information like flash sales, breaking news, or critical updates.
- Re-engagement: Notifications remind users to return to the PWA. If people haven’t used the app in a while, a gentle nudge could be all they need to re-engage.
- Personalization: Did you know PWAs can leverage user data for personalization? With just a few data points, you can send personalized notifications based on user preferences, past behaviors, or location. This makes notifications way more engaging, increasing users’ likelihood of engaging with you. Additionally, offline functionality ensures that users can receive and interact with notifications even without an internet connection.
Next.js Push Notification Setup
Photo by baranq from Shutterstock
Once you’ve created your PWA, it’s time to set up push notifications. MagicBell makes it extremely simple simple to implement and start sending push notifications.
You can find the Web Push Notification starter repository on the MagicBell Github. This tutorial will be referencing code from the repository.
First, you need to register a service worker. The service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. This involves calling specific functions to register listeners and handle actions. MagicBell does the heavy lifting for you, so you can focus on building your PWA.
Next, you need to subscribe the user to push notifications. This step involves getting the user’s permission to send them push notifications and then generating a subscription object that contains all the information your push notification service needs to send a message to that user. We will be using the MagicBell SDK to handle this process.
After subscribing the user, you need to send the subscription object to your server. This is typically done via a POST request to your server’s endpoint. The server will store the subscription object and use it to send push messages to the user.
Finally, you need to handle incoming push messages in your service worker. This involves listening for the 'push' event and displaying a notification when a message is received. You can also handle the 'notificationclick' event to define what happens when the user clicks on the notification. The last two steps are handled seamlessly by MagicBell.
Using a personal push notification server can offer more control, but established services provide user-friendly features and easier configuration.
1. Nail the Requirements First
For starters, you need a few things to set up push notifications. That includes:
- HTTPS hosting: You must have secure HTTPS hosting. Push notifications transmit sensitive data between the server and the user’s device. HTTPS encrypts this data, keeping it secure.
- Service worker: This is where the magic happens. A service worker script runs in the background and handles push notification events for you at scale.
- Manifest file: A PWA needs a manifest file because it gives the browser important application information. The web app manifest is crucial for enabling features such as push notifications, which enhance user engagement and experience.
One caveat: iOS users must first install the Progressive Web App (PWA) by adding it to their home screen before they can subscribe to push notifications, so tailored prompts for these users are necessary.
2. Configure the Service Worker
The service worker does most of the heavy lifting in push notifications for PWAs. To set this up, you’ll need to know JavaScript and understand how a push service establishes a communication channel for sending push notifications to users.
Create a public/sw.js
file and add the following code:
importScripts('https://assets.magicbell.io/web-push-notifications/sw.js');
3. Add the MagicBell ContextProvider
MagicBell provides a ContextProvider component that you need to wrap your app with. The component provides the MagicBell context to all components in the SDK and allows you to use the WebPush Button in your app.
You will need to generate a User JWT on your server and pass it in the Context Provider.
We generate the User JWT in the app/auth.ts
file, we use the use server
directive to ensure that the user JWT generated on the server.
'use server';
import jwt from 'jsonwebtoken';
export async function getUserToken() {
// Replace with your actual user ID or logic to retrieve it
const userId = '7f4baab5-0c91-44e8-8b58-5ff849535174';
const secret = process.env.MAGICBELL_SECRET_KEY!;
const apiKey = process.env.MAGICBELL_API_KEY!;
const payload = {
user_email: null,
user_external_id: userId,
api_key: apiKey,
};
const token = jwt.sign(payload, secret, {
algorithm: 'HS256',
expiresIn: '1y',
});
return token;
}
In the app/layout.tsx
file we wrap our app with the MagicBell provider and pass in the user token.
// ...
import Provider from "@magicbell/react/context-provider";
export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode; }>) {
const userToken = await getUserToken();
return (
<Provider token={userToken}>
<html lang="en">
{/* ... */}
</html>
</Provider>
);
}
Now we are ready to add the WebPushButton to our app!
4. Integrate the WebPushButton
Now that your app has MagicBell ContextProvider, you can start using the WebPushButton component.
Start by importing the WebPushButton
component from the @magicbell/react
package:
import WebPushButton from '@magicbell/react/webpush-button';
And then you can use the WebPushButton
component in your app:
<WebPushButton
renderLabel={({ status, error }) => {
switch (status) {
case 'loading':
return <Loading />;
case 'error':
return `Error: ${error}`;
case 'success':
return 'Unsubscribe';
default:
return 'Subscribe';
}
}}
serviceWorkerPath="/sw.js"
/>
The WebPushButton
handles notification permissions and subscriptions for you.
5. Send Notifications
You should now be able to open to your app and subscribe to push notifications. There are a few ways to send notifications - you can use the MagicBell Dashboard to send broadcasts, or you can use the MagicBell CLI.
In the Next.js example app we use the MagicBell Node.js client to create a broadcast. We start by creating a route handler fo sending notifications: src/app/api/send-notification/route.ts
, and import the MagicBell client.
import { Client } from 'magicbell-js/project-client';
We create a POST endpoint and get the user's external ID, title, and the content of the notification from the request body. And then use the MagicBell's project client to create a broadcast.
export async function POST(request: Request) {
loadEnvConfig(process.cwd());
try {
const client = new Client({
token: process.env.MAGICBELL_PROJECT_TOKEN,
});
const { externalId, title, content } = await request.json();
const { data } = await client.broadcasts.createBroadcast({
title: title,
content: content,
recipients: [
{
externalId,
},
],
});
return Response.json(JSON.stringify(data));
} catch (reason) {
// ...
}
}
5 Tips for Leveraging the Full Potential of Push Notifications
Setting up push notifications in a progressive web app is easy. If you have the development chops to build a PWA, you’ve got what it takes to manage push notifications and send them from your app.
However, it’s crucial to follow push notification best practices, whether you’re new to sending notifications or your existing subscribers just aren’t biting. Follow these tips to get the most results from your push notification campaigns. At each point in the process, ensure your configurations and connections are properly established to enhance user experience.
1. Segment Your Audience
Your subscribers don’t want to open messages that have nothing to do with them. Effective communication hinges on relevance, and that’s especially true for push notifications sent directly to the user's device. Segment your audience into different lists based on:
- Demographics
- Purchase history
- Behavior
Instead of sending the same message to everyone, creating separate lists gives you the power to speak to subscribers more personally. Not everyone will bite, but subscribers are much more likely to respond positively to segmented, personalized content.
2. Follow Best Practices for Notification Content
Photo by Charlotte May from Pexels
Who you message matters, but the content of the message itself is arguably the most essential part of any push notification campaign. You'll need to refine these campaigns over time to find what sticks, but these content best practices are a great place to start:
- Use rich media: Enhance notifications with images, GIFs, or videos. Visual elements grab attention faster than text and convey your message more effectively. For example, a notification about a new movie release could include a captivating still from the film, while a product promotion might show a short clip of the product in use.
- Always include a CTA: A call to action button encourages subscribers to take immediate action. For example, a notification about a sale might have "Shop Now" and "Learn More" buttons. This improves the user experience by providing clear next steps and increases the chances of conversion.
- Encourage interaction: Always allow users to interact with your notifications. This could be through options like "Yes" or "No," swipe actions, or a reply field.
3. Watch Your Timing
Messaging matters, but timing and frequency are also significant factors. Don’t send people dozens of notifications daily—that’s a recipe for mass unsubscribes. Analyzing user behavior to identify peak times across various operating systems can significantly improve response rates, so send notifications when users are most likely to be active.
For a global audience, consider timing your notifications for different time zones.
It’s also smart to set frequency caps. Too many notifications can lead to users opting out, while too few might cause them to forget about your business. When in doubt, allow users to customize their communication frequency preferences in the PWA settings.
4. Use Analytics to Improve Notifications
Photo by RoBird from Shutterstock
The great thing about push notifications is that they collect an immense amount of data on your subscribers’ preferences. Don’t let that data go to waste; analyze it to craft even more effective campaigns in the future.
Use analytics tools to track open rates, interaction rates, and conversion rates from your notifications. This data is invaluable in understanding what works and what doesn’t, especially when users receive push messages from your service.
You can also conduct A/B testing (also called split testing) campaigns. With this approach, you test different versions of a notification to see which elements perform the best, whether it’s adjustments to your messaging, images, or timing.
Don’t be afraid to adjust your notification strategy based on what you learn. The more data-driven your decisions, the more likely you’ll see gains in user engagement and app performance.
5. Ensure Secure Data Transmission
Push notifications process sensitive data, so security should be a priority. Ensure secure data transmission through:
- End-to-end encryption: Encrypt all data exchanged via push notifications, whether at rest or in transit. This process encrypts all data on the server side before sending, only decrypting it once it reaches the subscriber’s device. Vapid keys are essential for authenticating messages transmitted from the server to the Push Service, ensuring secure communication.
- Security protocols: Use Transport Layer Security (TLS) to keep data secure while in transit. TLS prevents attackers from intercepting the data while it travels to the user’s device.
- Framework compliance: Follow regulations like the European Union’s GDPR or California’s CCPA. These frameworks require explicit consent for data collection and provide users with control over their data. They’re some of the most stringent data privacy regulations in the world, so following these frameworks will set you up for improved security and compliance. Voluntary application server identification is also crucial for ensuring that only authorized servers can send messages to users, preventing unauthorized access.
Witness the Magic of PWA Notifications Firsthand
Screenshot from MagicBell
Progressive web apps balance the convenience of a native app with user expectations. Since users are less likely to visit a web app—especially if it isn’t open on their browser—push notifications are a much-needed lifeline for any PWA that relies on regular engagement.
The process outlined in this blog makes it a cinch to set up push notifications using progressive web applications, but there’s an easier way to get started. MagicBell’s real-time push notification inbox for PWAs gives users an all-in-one source for viewing and engaging with your messages.
Did we mention it’s easy to set up? Don’t just take our word for it: Sign up for MagicBell to see our powerful notifications in action.
Frequently Asked Questions
Can you send push notifications to all browsers?
Yes, to most browsers. Chrome, Firefox, Edge, and Safari all allow push notifications from progressive web apps. However, setting up notifications will differ by browser—especially for Safari, which behaves differently.
How do I measure the success of push notification campaigns?
Look at analytics on delivery rates, open rates, interaction rates, and conversion rates. Many push notification platforms include tools built into the platform for analyzing your performance, but you can also verify performance with third-party analytics tools.
Can I customize push notifications based on a user's location?
Yes, provided the user shared their location data with you. Location-based messaging is a great way to send hyper-relevant notifications on weather alerts, local news, or local retail offers.
However, it's best to give users more control over their data, so allow them to customize the information they share with you in their notification settings.