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 offers a ready-to-use Mercure-Hub cloud solution that provides a host of benefits, including:
- Unlimited requests and message sizes.
- Customizable domain name secured with HTTPS (for example, https://real-time.your-company.com).
- Effortless updates with just a click.
- Optimal performance and robust security powered by a private and dedicated VM.
- Available in 🇪🇺 Europe and 🇺🇸 USA.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Mercure-Hub cloud hosting solution!
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.