Mercure-Hub: Authentication of subscribers

This documentation is part of the Getting started guide. View the full guide here: How to get started with Mercure-hub.

👋 Welcome to the Stackhero documentation!

Stackhero provides a fully managed Mercure-Hub cloud service designed to make real-time data delivery simple and reliable. You get:

  • Unlimited requests and message sizes for complete flexibility.
  • A custom domain with built-in HTTPS security (for example, https://real-time.your-company.com).
  • Effortless one-click updates to keep your hub up to date with zero hassle.
  • High performance and strong security on a private, dedicated infrastructure.
  • Multiple regions: 🇪🇺 Europe and 🇺🇸 USA for low-latency delivery.

Get up and running fast: it takes just 5 minutes to launch your Mercure-Hub cloud hosting environment and start pushing 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!