Mercure-Hub: Getting started with Mercure-hub
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.
On the client side (your front end), simple JavaScript code that leverages the HTML5 SSE API is all you need.
Note: In this example, the subscriber is not authenticated. To make this example work, you must allow anonymous subscribers on the Stackhero dashboard.
const endpoint = '<XXXXXX>.stackhero-network.com';
const url = new URL('https://' + endpoint + '/.well-known/mercure');
// Add topics to listen to
url.searchParams.append('topic', `https://${endpoint}/users/1234`);
url.searchParams.append('topic', `https://${endpoint}/books/1`);
const eventSource = new EventSource(url);
// The callback is invoked each time an update is published
eventSource.onmessage = e => console.log(e);
On the server side (your back end), when you want to dispatch an update, simply send a POST request to the Mercure-hub API. Below is an example using Node.js along with the JsonWebToken and Request libraries:
const jwt = require('jsonwebtoken');
const request = require('request');
const endpoint = '<XXXXXX>.stackhero-network.com';
const publisherJwtKey = '<your publisher JWT key>';
// Define the data to dispatch
const data = {
// The topic where the data will be pushed
topic: `https://${endpoint}/books/1`,
// The data to be sent to the topic
data: JSON.stringify({
available: false,
date: new Date()
})
};
// Generate the bearer token
const bearer = jwt.sign(
{ mercure: { publish: [ data.topic ] } },
publisherJwtKey,
{
expiresIn: 60, // Token expires in one minute
noTimestamp: true // Do not include the 'issued at' timestamp to avoid "Token used before issued" errors
}
);
// Send the data to Mercure-hub so that it dispatches the update to clients
request.post(
{
url: `https://${endpoint}/.well-known/mercure`,
auth: { bearer },
form: data
},
(err, res) => err ? console.error(err) : console.log(res)
);
That's it! You now have a subscriber on the front end and a publisher on the back end working together seamlessly.