Middlewares

Middlewares provide a convenient way to inspect, filter or transform your Kafka messages before they reach the handler. A middleware receives the message and the next step of the pipeline, and whatever it passes to $next is what the handler receives. Not calling $next skips the handler for that message, which is then considered handled.

Sponsorship

Support Laravel Kafka by sponsoring me!

Laravel Kafka is free and Open Source software, built to empower developers like you. Your support helps maintain and enhance the project. If you find it valuable, please consider sponsoring me on GitHub. Every contribution makes a difference and keeps the development going strong! Thank you!

Become a Sponsor Want to hide this message? Sponsor at any tier of $10/month or more!

A middleware can be a closure:

use Junges\Kafka\Contracts\ConsumerMessage;

function (ConsumerMessage $message, callable $next) {
    // Perform some work here
    return $next($message);
}

Or a class implementing the Junges\Kafka\Contracts\Middleware interface. Middleware classes given by name are resolved from the service container, so their constructor can receive any dependency they need. They are resolved once, when the consumer handles its first message, and the same instance handles every message, so don't keep state about a single message in their properties:

use Illuminate\Log\LogManager;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\Middleware;

class LogMessages implements Middleware
{
    public function __construct(private LogManager $log) {}

    public function __invoke(ConsumerMessage $message, callable $next): mixed
    {
        $result = $next($message);

        $this->log->info('Kafka message handled', [
            'topic' => $message->getTopicName(),
            'offset' => $message->getOffset(),
        ]);

        return $result;
    }
}

In a consumer class , return the middlewares from the middleware method:

public function middleware(): array
{
    return [
        LogMessages::class,
        new RequireHeader('tenant'),
        function (ConsumerMessage $message, callable $next) {
            return $next($message);
        },
    ];
}

When building a consumer yourself, use the withMiddleware method, once for each middleware:

$consumer = \Junges\Kafka\Facades\Kafka::consumer(['orders'])
    ->withMiddleware(LogMessages::class)
    ->withMiddleware(new RequireHeader('tenant'))
    ->withHandler($handler);

Middlewares run in the order they are registered, so the first one wraps all the others. When failed messages are retried , the middlewares run again on every attempt, and an exception thrown by a middleware makes the message fail like one thrown by the handler.

To run middlewares for every consumer, register them with the consumerMiddleware method of the Kafka facade, usually in the boot method of a service provider:

use Junges\Kafka\Facades\Kafka;

public function boot(): void
{
    Kafka::consumerMiddleware([
        LogMessages::class,
        SetTenantFromHeaders::class,
    ]);
}

Global middlewares apply to every consumer created through the Kafka facade, including consumer classes , on any connection. They run before the middlewares of each consumer. They are kept when using Kafka::fake(), so your tests go through them as well.