You have successfully set up the client-side logic and registered a Service Worker, but the bridge to your server remains incomplete. The JavaScript in your Main.js handles subscriptions, while the sw.js file manages notifications once they arrive. To make this system functional, you must implement the backend endpoint that accepts messages from your server and pushes them to the subscribed users.
The Minishlink Web Push PHP library simplifies this process by handling the complex cryptographic operations required by the Web Push specification. Specifically, it generates the VAP (Vendored Authentication) and VP (Vendored Payload) encryption keys that are essential for secure message delivery. Without these keys, the browser cannot verify the authenticity of the notification.
Configuring the Server-Side Endpoint
First, ensure your server has the necessary dependencies installed via Composer:
composer require minishlink/web-push
Next, you need a secure endpoint on your web server (e.g., /push) to handle incoming requests. This endpoint will receive the subscription details from the client and store them in your database. It must also be capable of decrypting payloads sent by third-party notification services or sending messages directly if using a VAP key.
Here is a basic implementation pattern for the push controller:
use Minishlink\WebPush\Key;
use Minishlink\WebPush\MessageBuilder;
use Minishlink\WebPush\Response;
$pushManager = new \Minishlink\WebPush\PushManager();
// Initialize keys. In production, generate these securely once and store them.
$vapKeys = $pushManager->generateVAPKeyPair();
$keyStore = new Key\VolatileStorage($vapKeys); // Use a database for persistence in real apps
$subscriptionPayload = json_decode(file_get_contents('php://input'), true);
// 1. Store the subscription payload (keys, endpoint, user ID) in your DB here.
// 2. Decrypt and validate the message if necessary
$messageBuilder = new MessageBuilder();
$messageBuilder->setVAPKeyPair($keyStore->getVapKeys());
$messageBuilder->setTimeout(604800); // 7 days expiration
// Example: Sending a notification to a specific user's endpoint
// Note: You must map the user ID from your DB to their stored subscription payload
$subscription = getSubscriptionFromDB($userId);
if ($subscription) {
$response = $pushManager->sendNotification(
$subscription['endpoint'],
json_encode(['title' => 'New Comment', 'body' => 'You have a new comment on your post']),
['vapid' => $keyStore->getVapKeys()]
);
if ($response->getStatus() == Response::STATUS_SUCCESS) {
// Success handling
} else {
// Error handling
}
}
Handling Cryptographic Keys
A common pitfall is managing the VAP keys. The library requires a VAP public key to be included in every request sent to the browser, and the private key must be used to sign messages on the server. If you store these keys in VolatileStorage, they will reset every time you restart your PHP-FPM or Apache service, breaking all active subscriptions.
For any production environment, replace Key\VolatileStorage with a persistent storage class that retrieves your pre-generated VAP key pair from a secure location (e.g., environment variables, a database, or a secrets manager). This ensures that existing subscriptions remain valid across server restarts.
Storing Subscriptions Securely
The subscription payload sent by the browser contains sensitive cryptographic keys (p256dh and auth) required to decrypt messages. You must treat this data as highly confidential. Store these values in a secure database with strict access controls. Never log the full subscription payload, as it exposes private keys that could allow an attacker to hijack notifications or read encrypted payloads intended for other users.
When a user clicks the notification in your sw.js, you handle the navigation logic:
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
This ensures that even if the tab is closed, the user can still interact with your application upon clicking a push. However, remember that Web Push notifications only work on browsers that support the Service Worker API and require an active HTTPS connection. If SSL is not strictly enforced, the browser will block the registration of the Service Worker, rendering the entire system useless.
Conclusion
By integrating the Minishlink library with your existing JavaScript setup, you create a robust notification system. The key to success lies in secure key management and persistent storage of subscriptions. Once your server endpoint is configured to accept and process messages, your visitors will receive real-time updates regardless of their tab state.