Skip to content
Efficience IT
FR
·5 min read·Symfony

Mercure With Symfony: A Real-Time Progress Bar, Step by Step

By Romain Brillant

Mercure With Symfony: A Real-Time Progress Bar, Step by Step

A CSV import of several thousand lines, an export that takes two minutes, an order whose status changes: in all these cases, the user stares at a frozen page wondering whether anything is happening. Mercure solves this by pushing information to the browser the moment it exists. This article builds a concrete case end to end: a CSV import processed in the background by Symfony Messenger, with a progress bar that moves live.

Mercure in a Few Lines

Mercure is a publish and subscribe protocol built on Server-Sent Events (SSE). The browser opens a long-lived HTTP connection to a hub and subscribes to topics. The server publishes updates on those topics through a simple POST request to the hub, which forwards them to subscribers.

Compared with WebSockets, Mercure has the advantage of staying plain HTTP: no separate protocol, automatic reconnection handled by the browser, and compatibility with HTTP/2 and HTTP/3. It covers the most common case, the server informing the client. If the client needs to send a continuous stream to the server (games, fine-grained collaborative editing), WebSockets remain a better fit. Compared with polling, Mercure avoids hundreds of useless requests and shows information without delay.

Starting Project and Tested Versions

Every command and code sample below was run on December 1, 2026 on Ubuntu 26.04.1 LTS (WSL2), with Symfony 8.1.12, MercureBundle 0.7.0 (symfony/mercure component 0.10.0), Messenger 8.1.12, DoctrineBundle 3.4.2 and FrankenPHP 1.14.0, which ships the Mercure 1.1.6 hub. If FrankenPHP is new to you, our article What Is FrankenPHP, Exactly? covers its installation and its configuration with systemd.

We start from a blank Symfony project:

composer create-project symfony/skeleton /var/www/mercure-demo
cd /var/www/mercure-demo
composer require symfony/mercure-bundle symfony/messenger symfony/doctrine-messenger doctrine/doctrine-bundle symfony/twig-bundle

Preparing the Messenger Queue

Processing has to run in the background, otherwise the progress bar makes no sense. The queue is stored in a SQLite database, which avoids installing a database server. The extension is needed for Ubuntu's PHP, used by the console, and for FrankenPHP's PHP:

sudo apt install -y php8.5-sqlite3 php-zts-pdo-sqlite

The DoctrineBundle recipe generates a configuration that assumes the full ORM, and cache:clear fails with "The doctrine/orm package is required". Messenger only needs the connection:

# config/packages/doctrine.yaml
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
        routing:
            App\Message\ImportCsv: async
# .env.local
DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
MESSENGER_TRANSPORT_DSN=doctrine://default

If you are unsure which transport to pick, our Symfony Messenger vs PHP Enqueue comparison reviews the options.

Need support on your project?

Let's talk

Enabling the Hub Built Into FrankenPHP

Mercure 1.0 tightened its authorization model. The publisher_jwt and subscriber_jwt directives, still found in many tutorials, now make startup fail. Keys are declared in an issuer block:

localhost {
	root /var/www/mercure-demo/public
	encode zstd br gzip
 
	mercure {
		issuer https://localhost {
			publisher {
				jwt {env.MERCURE_JWT_KEY} HS256
			}
			subscriber {
				jwt {env.MERCURE_JWT_KEY} HS256
			}
		}
		anonymous
		debugger
	}
 
	php_server
}

The same secret key, at least 32 characters long, must be known to the hub and to Symfony. Generate it once and put it in .env.local and in a systemd override for FrankenPHP:

SECRET=$(openssl rand -hex 32)
sudo mkdir -p /etc/systemd/system/frankenphp.service.d
printf '[Service]\nEnvironment=MERCURE_JWT_KEY=%s\n' "$SECRET" | sudo tee /etc/systemd/system/frankenphp.service.d/override.conf
cat >> .env.local <<EOF
MERCURE_URL=https://localhost/.well-known/mercure
MERCURE_PUBLIC_URL=https://localhost/.well-known/mercure
MERCURE_JWT_SECRET=$SECRET
EOF

On the Symfony side, MercureBundle 0.7 speaks protocol 1.0 by default and refuses to compile without the iss, sub and client_id claims. The iss must match the issuer in the Caddyfile, and the cookie name must match the one the hub expects:

# config/packages/mercure.yaml
mercure:
    hubs:
        default:
            url: '%env(MERCURE_URL)%'
            public_url: '%env(MERCURE_PUBLIC_URL)%'
            cookie_name: '__Secure-mercure_access_token'
            jwt:
                secret: '%env(MERCURE_JWT_SECRET)%'
                publish: '*'
                claims:
                    iss: 'https://localhost'
                    sub: 'mercure-demo'
                    client_id: 'mercure-demo'

With MERCURE_URL and MERCURE_PUBLIC_URL set to https://localhost/.well-known/mercure and MERCURE_JWT_SECRET set to the generated value, restart FrankenPHP and check that the hub accepts a subscription:

sudo systemctl daemon-reload && sudo systemctl restart frankenphp
curl -sN -D - --max-time 5 'https://localhost/.well-known/mercure?match=test'

The expected response is HTTP/2 200 with content-type: text/event-stream, after which the connection stays open.

Publishing Progress From a Messenger Handler

The message carries the import identifier and the file path:

namespace App\Message;
 
final class ImportCsv
{
    public function __construct(
        public readonly string $importId,
        public readonly string $path,
    ) {
    }
}

The handler processes lines one by one and publishes progress after each of them. The usleep() call simulates business processing to make the progress visible:

namespace App\MessageHandler;
 
use App\Message\ImportCsv;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
 
#[AsMessageHandler]
final class ImportCsvHandler
{
    public function __construct(private readonly HubInterface $hub)
    {
    }
 
    public function __invoke(ImportCsv $message): void
    {
        $lines = file($message->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $rows = array_slice($lines, 1);
        $total = count($rows);
        $topic = 'https://localhost/imports/'.$message->importId;
 
        foreach ($rows as $index => $line) {
            str_getcsv($line, escape: '');
            usleep(100000);
 
            $this->hub->publish(new Update($topic, json_encode(['done' => $index + 1, 'total' => $total]), private: true));
        }
    }
}

In a more structured architecture, this handler becomes an adapter that calls the domain, as we show with Messenger at the core of a hexagonal architecture.

Subscribing in the Browser

The controller generates the import identifier before the file is sent. The page therefore subscribes as soon as it is displayed and misses none of the first updates:

namespace App\Controller;
 
use App\Message\ImportCsv;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
 
final class ImportController extends AbstractController
{
    #[Route('/', name: 'import_index', methods: ['GET'])]
    public function index(): Response
    {
        $id = bin2hex(random_bytes(8));
 
        return $this->render('import/index.html.twig', [
            'id' => $id,
            'topic' => 'https://localhost/imports/'.$id,
        ]);
    }
 
    #[Route('/import/{id}', name: 'import_start', requirements: ['id' => '[a-f0-9]{16}'], methods: ['POST'])]
    public function start(string $id, Request $request, MessageBusInterface $bus): JsonResponse
    {
        $file = $request->files->get('csv');
        $path = $file->move($this->getParameter('kernel.project_dir').'/var/imports', $id.'.csv')->getPathname();
 
        $bus->dispatch(new ImportCsv($id, $path));
 
        return $this->json(['id' => $id], Response::HTTP_ACCEPTED);
    }
}

In the template, the mercure() Twig function builds the subscription URL with the right match= parameter. The subscribe option sets a cookie holding a token that authorizes the browser to receive the private updates of that topic, and only that one:

<form id="import" action="{{ path('import_start', {id: id}) }}">
    <input type="file" name="csv" accept=".csv" required>
    <button>Import</button>
</form>
<progress id="progress" value="0" max="1"></progress>
<p id="status">Waiting</p>
<script>
    const progress = document.getElementById('progress');
    const status = document.getElementById('status');
    const source = new EventSource({{ mercure(topic, {subscribe: topic})|json_encode|raw }});
 
    source.onmessage = (event) => {
        const { done, total } = JSON.parse(event.data);
        progress.max = total;
        progress.value = done;
        status.textContent = `${done} / ${total} lines`;
        if (done === total) {
            source.close();
        }
    };
 
    document.getElementById('import').addEventListener('submit', (event) => {
        event.preventDefault();
        fetch(event.target.action, { method: 'POST', body: new FormData(event.target) });
    });
</script>

Running the Worker and Testing

php bin/console messenger:setup-transports
php bin/console messenger:consume async -vv

When you send a 50-line CSV, the bar fills up in five seconds. The worker logs one POST https://localhost/.well-known/mercure line with a 200 per update, published in 4 to 8 ms, then handled successfully.

Checking That Updates Stay Private

A token-less "spy" that subscribes to every import with a URL pattern proves it:

curl -sN 'https://localhost/.well-known/mercure?match_urlpattern=https://localhost/imports/:id'

Without private: true, it receives all 50 data: {"done":1,"total":50} lines. With private updates, it only receives the : keep-alive comments, while the browser, holding its cookie, sees its bar progress. The built-in UI, enabled by the debugger directive, is available at /.well-known/mercure/debug/ to subscribe or publish by hand.

Going to Production

Serving the hub on the same origin as the application, as here, avoids any CORS configuration. If the hub lives on another subdomain, the cors_origins directive must explicitly list the allowed origins, because the authorization cookie requires credentialed requests. Behind a reverse proxy that terminates TLS, prefix the site address with http:// to disable Caddy's HTTPS, and make sure the proxy does not buffer the stream. Our analysis of Traefik vs Nginx in production helps pick that proxy. The default transport, bolt, keeps update history on a single node. Finally, remove anonymous if no public update is planned.

Pitfalls We Ran Into

  • topic= no longer exists: a Mercure 1.0 hub answers 400. Use match= or match_urlpattern=, which is what the mercure() Twig function does.
  • publisher_jwt rejected at startup: move to the issuer block rather than enabling compatibility mode, which relaxes token checks.
  • The cookie name: in debug mode, Symfony names the cookie mercure_access_token, while the hub reads __Secure-mercure_access_token. Without cookie_name, the browser receives nothing.
  • A cookie invisible in DevTools: its path is limited to /.well-known/mercure. Check that it is there with curl -s -D - -o /dev/null https://localhost/.
  • "attempt to write a readonly database": the SQLite database created by the console is not writable by the frankenphp user. ACLs must include the mask: setfacl -R -m u:frankenphp:rwX -m m::rwX var.
  • The local certificate: to publish to https://localhost, the console's PHP must trust Caddy's local authority, which you copy into /usr/local/share/ca-certificates.
  • The worker keeps the old code: restart messenger:consume after every handler change.
  • frankenphp validate fails: the MERCURE_JWT_KEY variable only exists in the service environment. Provide a value for the duration of the validation.

Going Further

Have a project in mind?

Our team replies within 48 hours to look at your needs and suggest a suitable approach.

Contact us

Frequently asked questions

No, if the application runs on FrankenPHP: the Mercure hub is built in and is enabled with a mercure directive in the Caddyfile. A standalone hub remains an option if the application runs on Nginx and PHP-FPM.

Since Mercure 1.0, the topic= parameter has been replaced by match= for an exact match and match_urlpattern= for a pattern. A 1.0 hub rejects the old parameters with a 400 error.

By publishing private updates (private: true) and giving the browser a JWT cookie that authorizes it to listen to its own topics only, through the subscribe option of the mercure() Twig function.

Related articles