Skip to content

Real-Time Laravel: Implementing Native Mercure Broadcasting

By Rogers Sampaio Santos Published: 6 tags 4 min read

Discover how Laravel 13.32's native Mercure driver simplifies real-time updates by replacing persistent WebSockets with efficient, unidirectional Server-Sent Events (SSE).

1. Transitioning from WebSockets to Native Mercure

The landscape of real-time web applications has traditionally been dominated by WebSocket technology, which provides persistent, bi-directional communication channels. While powerful, WebSockets introduce significant overhead, requiring servers to maintain thousands of open connections and manage complex handshake states. For many Laravel applications where the primary goal is pushing updates from the server to the client, this persistence is often overkill. Server-Sent Events (SSE) offer a superior, lightweight alternative by utilizing standard HTTP connections for unidirectional data flow.

Laravel 13.32 introduces native support for the Mercure protocol, allowing developers to shift from complex socket management to a stateless, event-driven architecture. Mercure excels in public broadcasting scenarios—such as dashboard updates or notification feeds—by leveraging existing HTTP/2 infrastructure, drastically reducing memory usage on both the application server and the client side. This transition significantly simplifies infrastructure requirements compared to managing a dedicated WebSocket server.

To begin, ensure your application is configured to use the Mercure driver. Update your .env file to define the connection and verify your config/broadcasting.php setup:

BROADCAST_CONNECTION=mercure
MERCURE_URL=https://mercure.example.com/.well-known/mercure
MERCURE_PUBLIC_URL=https://mercure.example.com/.well-known/mercure

Within config/broadcasting.php, ensure the mercure connection array correctly points to these environment variables. This setup allows Laravel to dispatch events directly to your Mercure hub via standard HTTP requests.

2. Implementing Event Broadcasting with Mercure

Implementing broadcasting remains straightforward, as Laravel abstracts the underlying driver behind the familiar ShouldBroadcast interface. When an event implements this interface, Laravel’s broadcast system handles the necessary serialization and dispatching. For Mercure, this means converting your event payload into a streamlined JSON object, which is then pushed to the hub.

Focus on minimizing the payload size to ensure fast transmission. Instead of broadcasting full Eloquent models, consider sending only the essential properties needed by the frontend to react to the change. Below is a sample implementation of a test event:

namespace App\Events;

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class DataUpdated implements ShouldBroadcast
{
    use SerializesModels;

    public function __construct(public int $id, public string $status) {}

    public function broadcastOn(): array
    {
        return ['public-updates'];
    }
}

You can test the flow by firing the event from an Artisan command or a route. When triggered, the application will perform a synchronous HTTP request to the Mercure hub, which then asynchronously propagates the event to all connected clients. This eliminates the need for a separate queue worker if you prefer immediate updates, though async dispatching remains available for high-throughput requirements.

3. Architecting Data Flows with Filesystem Integration

Modern applications frequently process files—such as image uploads or report generation—that require real-time feedback upon completion. Integrating Mercure with Laravel’s file storage helpers allows you to create seamless user experiences. By utilizing the moveToDisk or copyToDisk methods, you can ensure file persistence before notifying the UI that an asset is ready.

To avoid race conditions where a client might attempt to load a file before it has finished moving, always dispatch the broadcast event strictly after the filesystem operation confirms success. This sequence guarantees that your frontend only receives notifications for fully available assets.

public function processUserUpload(Request $request)
{
    $path = $request->file('report')->store('temp');
    
    // Move to final destination
    Storage::disk('s3')->putFileAs('reports', $path, 'report.pdf');
    Storage::disk('local')->delete($path);

    // Broadcast status update
    event(new ReportReadyEvent($userId, 'report.pdf'));
}

This architecture ensures that the broadcast signal acts as the definitive source of truth for the client, triggering UI updates only when the server is fully ready to serve the processed file.

4. Frontend Consumption and Production Readiness

One of the most compelling aspects of Mercure is its simplicity on the frontend. Since it relies on standard Server-Sent Events, you can subscribe to channels using the browser’s native EventSource API, avoiding the need for heavy, external socket libraries. For more complex integrations, you may still utilize Laravel Echo, but for read-only event propagation, a vanilla implementation is often sufficient.

const eventSource = new EventSource('https://mercure.example.com/.well-known/mercure?topic=public-updates');

eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Update received:', data);
    // Update DOM accordingly
};

Security remains paramount when using Mercure. For private channels, ensure your Mercure hub is configured with a strict JWT secret and that your Laravel application issues signed tokens during the handshake process. For most production needs, stick to Mercure for read-only, scalable event propagation, reserving traditional WebSockets for scenarios specifically requiring true bi-directional, persistent client-to-server interaction.

Sources

Share
X LinkedIn Facebook