Quickstart: Publish an update to a Mercure Hub
mainTo publish real-time updates, you need to configure a Hub instance. This requires the Hub's URL and a TokenProvider that generates valid JWTs for authentication.
- Define your
HUB_URLandJWT_SECRET. - Create a
LcobucciFactoryusing your secret. - Create a
FactoryTokenProvider(passing the factory and the topics you wish to publish to, e.g.,['*']for all topics). - Instantiate the
Hubwith the URL and provider. - Use
$hub->publish()with a newUpdateobject containing the target topic (URL) and the payload.
// change these values accordingly to your hub installation
const HUB_URL = 'https://demo.mercure.rocks/.well-known/mercure';
const JWT_SECRET = '!ChangeThisMercureHubJWTSecretKey!';
// Set up the JWT token provider
// Alternatively, you can use the \Symfony\Component\Mercure\Jwt\StaticTokenProvider if you already have a JWT token
$jwFactory = new \Symfony\Component\Mercure\Jwt\LcobucciFactory(JWT_SECRET);
$provider = new \Symfony\Component\Mercure\Jwt\FactoryTokenProvider($jwFactory, publish: ['*']);
$hub = new \Symfony\Component\Mercure\Hub(HUB_URL, $provider);
// Serialize the update, and dispatch it to the hub, that will broadcast it to the clients
$id = $hub->publish(new \Symfony\Component\Mercure\Update('https://example.com/books/1.jsonld', 'Hi from Symfony!'));