Skip to content

Middleware ​

Client and ClientHandler accept middleware implementing Fetch\Interfaces\Middleware or a callable. A callable receives the outgoing PSR-7 request and a $next function. Middleware may modify the request and pass it onward.

php
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use React\Promise\PromiseInterface;

$handler = fetch_client()->getHandler();
$handler->addMiddleware(static function (
    RequestInterface $request,
    callable $next,
): ResponseInterface|PromiseInterface {
    return $next($request->withHeader('X-Client-Name', 'example'));
});

Use a class implementing Middleware when behavior needs dependencies or reuse. Middleware registered on the shared helper client persists until it is replaced or reset.

The pipeline applies to the regular buffered request path. Streaming requests use a separate Guzzle path and bypass this middleware pipeline. A middleware may see a promise in async mode, so do not treat it as a PSR response until it resolves.

php
<?php

declare(strict_types=1);

require dirname(__DIR__, 3).'/vendor/autoload.php';

use Fetch\Interfaces\Response as FetchResponse;
use Fetch\Testing\MockResponse;
use Fetch\Testing\MockServer;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use React\Promise\PromiseInterface;

MockServer::fake([
    'GET https://api.example.test/v1/profile' => MockResponse::json([
        'id' => 1,
    ]),
]);
MockServer::preventStrayRequests();

$handler = fetch_client(reset: true)->getHandler();
$handler->addMiddleware(static function (
    RequestInterface $request,
    callable $next,
): ResponseInterface|PromiseInterface {
    return $next($request->withHeader('X-Request-Id', 'demo-123'));
});

$response = $handler->get('https://api.example.test/v1/profile');

if (! ($response instanceof FetchResponse) || ! $response->successful()) {
    throw new RuntimeException('The middleware example failed.');
}

Released under the MIT License.