Mercure-Hub: Authentication of Subscribers

This documentation is part of the Getting Started guide. You can view the complete guide here: How to Get Started with Mercure-hub.

👋 Welcome to the Stackhero documentation!

Stackhero offers a fully managed Mercure-Hub cloud service designed to simplify and ensure reliable real-time data delivery. You benefit from:

  • Unlimited requests and message sizes for total flexibility.
  • A custom domain with integrated HTTPS security (for example, https://real-time.your-company.com).
  • One-click updates to keep your hub up to date effortlessly.
  • High performance and enhanced security on a private, dedicated infrastructure.
  • Multiple available regions: 🇪🇺 Europe and 🇺🇸 USA for low-latency delivery.

Get started quickly: it only takes 5 minutes to launch your Mercure-Hub cloud hosting environment and start sending real-time updates to your applications.

In the earlier examples, subscribers were not authenticated and you needed to allow "anonymous subscribers" on the Stackhero dashboard.

To authenticate subscribers, you generate a JWS (JSON Web Signature) using the 'Subscriber JWT key' defined in the Stackhero dashboard. The JWS is then sent using either browser cookies or the authorization header.

Since the Server-Sent Events API does not support custom header definitions, cookies must be used. However, using cookies implies that your Mercure-hub server and client need to share the same domain (or subdomain).

If you wish to use SSE across different domains, consider an EventSource polyfill that allows header definitions. One option is available at https://github.com/Yaffle/EventSource.

First, generate a JWS for your client on your server side. An example is available in backend/subscriberJwsGenerator.js. Simply input your subscriber JWT and run the script using node subscriberJwsGenerator.js.

Then, on the front end, in the file frontend/subscriberWithAuthorization.html, fill in your endpoint and the generated JWS. Open the file in your browser and Mercure-hub will now work with authentication!

Don't forget to uncheck "Allow anonymous subscribers" in the Stackhero dashboard!