- php ^8.5
- symfony ^7.4 || ^8.0
- jul6art/core-bundle ^2.0
- mercure (symfony/mercure-bundle ^0.3)
composer require jul6art/push-bundleThen Download the mercure hub depending on your operating system and install it in the root of your project. For each release, the assets section list operating systems implementations. The folder must contain the mercure bin. Rename this folder mercure.
npm install event-source-polyfilland import it on client side to make push works on IE and Edge
Go to jwt.io and put your future mercure secret key (default it's !ChangeMe!) in the verify signature textarea and this array in the payload textarea
{
"mercure": {
"publish": []
}
}Because the array is empty, the Symfony app will only be authorized to publish public updates (see the authorization section of symfony/mercure-bundle for further information).
THen store the generated token in your .env file as MERCURE_JWT_TOKEN parameter
The default token is signed with the secret key: !ChangeMe!
CORS_ALLOWED_ORIGINS is the client URL and port. It can be * or a list of domains ADDR is the server url and 3000 is the port for mercure server
JWT_KEY='!ChangeMe!' ADDR='localhost:3000' ALLOW_ANONYMOUS=1 CORS_ALLOWED_ORIGINS="http://localhost:80" ./mercure/mercure
⚠️ By default, push messages are async so you need to launch a crawler in a terminal to dequeue messages and send it
bin/console messenger:consume async_priority_high --time-limit 600Server side
use ApiPlatform\Metadata\ApiResource;
#[ApiResource(mercure: true)]
class SomeTopic
{
}Client side
import {EventSourcePolyfill} from "../polyfills/Polyfills";
export default class MercureProvider {
provide = () => {
const publishUrl = new URL('http://publish.url:3000/hub');
publishUrl.searchParams.append("topic", "/some_topic");
publishUrl.searchParams.append("topic", "/some_topic/{id}");
const es = new EventSourcePolyfill(publishUrl, {
headers: {
'Authorization': 'Bearer ' + YOUR_MERCURE_JWT_TOKEN
}
});
es.onmessage = e => {
const data = JSON.parse(e.data);
const regex = /\/api\/(?<type>\w+)\//gm;
const match = regex.exec(data['@id']);
if (null !== match) {
const event = new CustomEvent(match.groups.type, { "data": data });
document.dispatchEvent(event);
}
};
}
};
// somewhere else
document.addEventListener('...', function() {
// what you need
});Server side
use Jul6Art\PushBundle\Service\Traits\PusherAwareTrait;
class SomeService
{
use PusherAwareTrait;
public function notify(): void
{
$this->pusher->push('/some/topic', ['test' => true]);
}
}push:
async: falsepush:
routing:
'PathToSomeAsyncMessage': async_priority_highCan be async_priority_high or async_priority_low or sync
The Asyncable annotation is now a PHP attribute: Jul6Art\PushBundle\Attribute\Asyncable.
My Entity
use App\Event\MyClassEvent;
use Doctrine\ORM\Mapping as ORM;
use Jul6Art\PushBundle\Attribute\Asyncable;
#[ORM\Entity(repositoryClass: MyClassRepository::class)]
#[Asyncable(eventClass: MyClassEvent::class)]
class MyClass
{
}My EntityEvent
The event class must accept the entity as its only constructor argument and must
extend Jul6Art\CoreBundle\Event\AbstractEvent.
<?php
declare(strict_types=1);
namespace App\Event;
use App\Entity\MyClass;
use Jul6Art\CoreBundle\Event\AbstractEvent;
class MyClassEvent extends AbstractEvent
{
public const string CREATED = 'event.my_class.created';
public const string DELETED = 'event.my_class.deleted';
public const string EDITED = 'event.my_class.edited';
public const string VIEWED = 'event.my_class.viewed';
public function __construct(private MyClass $myClass)
{
parent::__construct();
}
public function getMyClass(): MyClass
{
return $this->myClass;
}
public function setMyClass(MyClass $myClass): static
{
$this->myClass = $myClass;
return $this;
}
}All actions in listeners who listen these event class consts will be async
You can also specify which doctrine events you want to track
#[ORM\Entity(repositoryClass: MyClassRepository::class)]
#[Asyncable(eventClass: MyClassEvent::class, events: ['postLoad', 'postPersist'])]
class MyClass
{
}Available events are
- postLoad
- postPersist
- postUpdate
- preRemove
Everything above pushes messages you write yourself. This part pushes them for you: annotate an entity, and every insert, update and delete on it emits a small Mercure update.
use Jul6Art\PushBundle\Attribute\BroadcastableEntity;
#[ORM\Entity]
#[BroadcastableEntity]
class Page { … }
#[BroadcastableEntity(type: 'CmsPage', changedFields: ['title', 'publishedAt'])]
class BlogPost { … }Mercure\EntityChangePublisher reads the attribute on Doctrine's onFlush / postFlush. There
is nothing else to wire — but there are three things to know before relying on it.
{"type":"Page","iri":"/api/pages/12","id":12,"action":"updated",
"topic":"/organizations/7/feed","at":"2026-08-20T09:12:44.318+00:00","actorId":3,"etag":"a1b2c3d4e5f6",
"changedFields":["title"]}A subscriber receives everything published on a topic it is allowed to listen to, without passing through a voter. Putting a field value in the payload would therefore broadcast it past every access rule you have. Consumers refetch through the API, which is where those rules live.
at is the instant of the flush, to the millisecond (3.4). A page that wants to know whether a
change came after it was rendered compares at with the instant its request started
(REQUEST_TIME_FLOAT): a save and the page its redirection renders fall in the same second.
⚠️ actorIdsays who, never where. The same account in another tab or on another device signs its changes alike: a subscriber that ignores "its own" changes byactorIdleaves those other screens stale. Decide on the state — re-read, or compareatwith the page's own instant.
changedFields is a whitelist, not a diff: only the intersection of what actually changed
with what the attribute names is exposed, so a client can decide whether a change concerns it
without learning about the fields you did not list.
The bundle publishes on whatever Mercure\FeedTopicResolverInterface returns, and ships
GlobalFeedTopicResolver — everything on /global/feed. That is right for a single tenant and a
leak for two.
final class OrganizationFeedTopicResolver implements FeedTopicResolverInterface
{
public function resolveTopic(object $entity): string
{
if ($entity instanceof Organization) {
return '/organizations/'.$entity->getId().'/feed';
}
if (method_exists($entity, 'getOrganization')) {
$organization = $entity->getOrganization();
// A tenant-scoped row with no tenant — a super-admin account, an orphan.
return $organization instanceof Organization
? '/organizations/'.$organization->getId().'/feed'
: '/admin/feed';
}
return '/global/feed';
}
}push:
mercure:
topic_resolver: App\Mercure\OrganizationFeedTopicResolver
⚠️ Do not let a tenant-scoped entity fall back to the shared topic. Every tenant user is subscribed to/global/feed, so a row landing there leaks its existence and triggers a reload for everyone. The example routes it to/admin/feed, which only an administrator's token covers. This mistake is silent: the feed keeps working, for too many people.
The topic is also how a burst is grouped: more than EntityChangePublisher::BURST_THRESHOLD
entities of one type on one topic in a single flush collapse into a single action: "bulk" event
carrying a count. Importing 500 rows then costs one reload per subscriber instead of 500.
The publisher listens to flushes. A DQL or SQL bulk write — UPDATE … WHERE id IN (…), a
CASE WHEN reorder, a cron that expires a batch — bypasses the UnitOfWork: no flush, no
publication, and every screen that follows the entity stays stale until it reloads. Announce what
the statement changed once it has run:
$ids = $this->quotes->idsToExpire($now);
$this->connection->executeStatement('UPDATE quote SET status = :expired WHERE id IN (:ids)', /* … */);
$this->publisher->announce(
array_map(fn (int $id): Quote => $this->entityManager->getReference(Quote::class, $id), $ids),
'updated',
['status'],
);The entities leave as a flush's would: same topic resolver, same whitelist of changedFields,
same burst coalescence. A reference is enough, but your resolver may load it to read its tenant —
pass loaded entities when there are many. The action is created, updated, deleted or
restored; bulk is the coalescence's to decide.
A statement that cannot load what it changed — a reconciliation that rewrites a tenant's rows in SQL to stay in constant memory, a retention purge — announces the batch instead (3.6), with any entity of its class on its topic and the number of rows:
$count = $this->connection->executeStatement('UPDATE stock_level SET quantity = 0 WHERE organization_id = ?', [$id]);
$this->publisher->announceBulk($this->stockLevels->findOneBy(['organization' => $id]), $count);Subscribers receive one action: "bulk" event with that count and no id, exactly what a flush of
as many rows would have sent.
Publishing inside postFlush means an HTTP call inside $em->flush(). A slow hub makes a slow
response; an unreachable one throws, and the user gets a 500 on a write that succeeded.
Mercure\BufferingHub decorates the hub so publish() only fills an in-memory buffer, and
Mercure\MercureDrainListener empties it on kernel.terminate — after the response has left —
on console.terminate for commands, and after every message a Messenger worker handles or fails
(3.5). A hub failure there is logged and swallowed.
⚠️ Amessenger:consumeworker is a single command: itsconsole.terminatecomes when it stops, an hour later with--time-limit=3600. Before 3.5, what its handlers flushed waited in the buffer until then. A handler that must publish during a long message (a progress bar) still drains the buffer itself:BufferingHub::drain().
It is on by default. The trade is explicit: between the response and the drain there is a millisecond-scale window where the client has been told "saved" and subscribers have not heard yet, and if the process dies in between those updates are lost. No data is lost — the row is committed — only a notification, and the next page load shows the new state anyway.
push:
mercure:
buffering: false # publish inline; a hub outage becomes a 500A subscriber authenticates with an access token granting subscribe on its topics, and an
EventSource cannot send an Authorization header — hence a cookie scoped to the hub path. Since
Mercure 1.0 there is no other way: the authorization query parameter is gone (RFC 9700 forbids a
token in a URL). Mercure\SubscriberCookieFactory mints both, with the hub's own token factory:
configure the hub for the protocol 1.0, with the claims a 1.0 hub requires.
mercure:
hubs:
default:
url: '%env(MERCURE_URL)%'
public_url: '%env(MERCURE_PUBLIC_URL)%'
jwt:
secret: '%env(MERCURE_JWT_SECRET)%'
publish: ['*']
claims:
iss: '%env(MERCURE_JWT_ISSUER)%' # an issuer the hub trusts (its `issuer` block)
aud: '%env(MERCURE_JWT_AUDIENCE)%' # the hub's `resource_identifier`
sub: my-app
client_id: my-appThe bundle ships the endpoint the browser calls before opening its EventSource
(Controller\MercureTokenController): it sets the subscriber cookie and returns
{ "subscribed": [...], "patterns": [...] }, prefixed as the token grants them. It declares no
route — route to it under the name and path your front end uses (admin-bundle's
admin.mercure.token_route names it):
# config/routes/push.yaml
admin_mercure_token:
path: /admin/mercure-token
controller: Jul6Art\PushBundle\Controller\MercureTokenController
methods: [GET]# config/packages/push.yaml
push:
mercure:
subscriber:
provider: App\Mercure\SubscriptionProvider # default: GlobalFeedSubscriptionProvider
access: IS_AUTHENTICATED_FULLY # default; any attribute isGranted() takesWhich topics an account may subscribe to stays in your application — it is an authorisation decision and the token's grant is what enforces it on the hub. Write it as a provider:
final readonly class SubscriptionProvider implements SubscriptionProviderInterface
{
public function subscriptionFor(UserInterface $user): Subscription
{
\assert($user instanceof User);
return $user->getOrganization() instanceof Organization
? new Subscription([OrganizationFeedTopicResolver::topicFor($user->getOrganization())])
: new Subscription(['/platform/feed'], patterns: ['/organizations/:id/feed']);
}
}Derive the list from the account, never from a request parameter, and throw an
AccessDeniedException when it may hear nothing. The default, GlobalFeedSubscriptionProvider,
gives every account /global/feed: right for a single tenant only. The endpoint is registered with
a hub and the security component; access may be IS_AUTHENTICATED (remember-me sessions too), a
role or a voter attribute.
An endpoint of another shape — a second area with its own access rule, a body that carries more —
keeps its own controller and lets Mercure\SubscriberTokenResponder do the rest:
return $responder->respond(new Subscription($topics, $patterns), ['hubUrl' => $this->hubUrl]);The extra keys never replace subscribed or patterns. Doing it by hand with the factory:
$subscription = $factory->subscription($topics); // ← prefixed, as the token grants them (3.2)
$token = $factory->createToken($topics);
$response = new JsonResponse(['subscribed' => $subscription['topics'], 'patterns' => $subscription['patterns']]);
$response->headers->setCookie($factory->createCookie($token));Hand the same list back in the response so the front end subscribes to exactly what the token allows
(match=<topic>, match_urlpattern=<pattern>, and withCredentials: true so the cookie goes
along); deriving it twice is how the two drift.
⚠️ *is a wildcard on both sides. A grant of['*']covers every topic, present and future. Convenient for an administrator, a tenant leak for anyone else.
A family of channels — every organisation's feed — is a URL Pattern since Mercure 1.0, which
dropped URI templates: /organizations/:id/feed, not {id}. Grant it as one (3.1), and let the
front end listen with match_urlpattern=:
$token = $factory->createToken(['/platform/feed'], patterns: ['/organizations/:id/feed']);
$response = new JsonResponse(['subscribed' => ['/platform/feed'], 'patterns' => ['/organizations/:id/feed']]);A relative pattern resolves against the hub's base URL — its pinned resource_identifier — exactly
like the relative topics it is compared with.
⚠️ Serve the hub under the application's own host. The cookie is host-only andSameSite=Strict: a browser never sends it to a hub on another site. Relay/.well-known/mercureunder the application's domain.
⚠️ Pin the audience. A 1.0 hub derives its resource identifier — theauda token must carry — from each request, and behind a TLS-terminating proxy or several domains that is rarely the public URL. Set the hub'sresource_identifierand the same value inclaims.aud.
The cookie bears the name the hub reads (cookie_name of the hub, __Secure-mercure_access_token
by default, a name that requires HTTPS); push.mercure.cookie_secure: false exists only for a
plain-http workstation, with a hub cookie_name without the __Secure- prefix.
push.mercure.jwt_secretandpush.mercure.cookie_nameare gone, and refused: the factory signs with the hub's factory (mercure.hubs.<name>.jwt) and names the cookie as the hub does.symfony/mercure^0.9 andsymfony/mercure-bundle^0.6: the protocol 1.0 by default. The hub must be a Mercure 1.x hub — or a 1.x hub inprotocol_version_compatibility 8while other applications still speak 0.x.- Subscribers:
topic=becomesmatch=, and the token travels in the cookie only.
Applications sharing a hub publish the same topic names — /organizations/7/feed is organisation 7
of EVERY database. Without a prefix, a subscriber granted that topic in one application receives
what the others publish on it. Give each application its corner of the hub:
push:
mercure:
topic_prefix: '/shop'The bundle applies it in one place per side, and your resolvers keep returning topics without it:
EntityChangePublisherpublishes on/shop/organizations/7/feed, and echoes that topic in the payload — a front end filtering onpayload.topiccompares the full topic;SubscriberCookieFactory::createToken()grants the prefixed topics and patterns, andsubscription()gives the same lists for the response body;- a grant of
*becomes the pattern/shop/*: every topic of THIS application, not of the hub; - what you publish yourself goes through
Mercure\TopicPrefix::update(), the prefixed equivalent ofnew Update(…):
$this->hub->publish($this->topics->update('/users/'.$user->getId().'/notifications', $json, private: true));A topic written as an absolute IRI keeps its scheme and host and takes the prefix at the start of its
path: https://example.org/shop/organizations/7/feed (3.2.1). Prefixing is idempotent: a topic that
already carries the prefix is left as it is. Empty — the
default — keeps 3.1's behaviour, right only for an application alone on its hub.
⚠️ The hub's key stays shared. The prefix keeps each application's subscribers on its own topics; it does not stop a compromised application from publishing on another one's.
With push.async: true — the default — this bundle routes
Symfony\Component\Mercure\Update to the async_priority_high transport, so a worker
publishes it instead of the request. That is a second way of solving the same problem the
buffering hub solves, and running both is not twice as safe:
push:
async: false # Update is not routed; the (buffering) hub publishes directly
⚠️ Routing toasync_priority_highrequires a worker consuming that transport. An application whose supervisor only runsmessenger:consume asyncwill queue every real-time update into a transport nobody drains, and the feed stops — silently, with the rows committed and the queue growing. Check your worker before leavingasync: true, and remember that an application with no#[Asyncable]entity has nothing else to gain from it.
No hub, no publishing — silently. The whole real-time stack is registered only when the
application configures mercure.hubs; without it, #[BroadcastableEntity] emits nothing and
reports nothing. That is deliberate — an application can install this bundle for its Messenger
side alone — but it means "my events never arrive" and "I never configured a hub" look identical.
composer qa # coding standards, Rector, static analysis and tests
composer test # PHPUnit
composer phpstan # PHPStan, level max
composer cs # PHP-CS-Fixer, writes the fixes
composer rector # Rector, writes the fixesThe Push Bundle is open-sourced software licensed under the MIT license.
© 2026 jul6art
