Skip to main content

Enable Streaming on Request

$request = (new HttpRequest(
    url: 'https://api.example.com/stream',
    method: 'GET',
    headers: ['Accept' => 'text/event-stream'],
    body: '',
    options: [],
))->withStreaming(true);
// @doctest id="8977"

Consume Chunks

foreach ($client->withRequest($request)->stream() as $chunk) {
    // parse or forward chunk
    echo $chunk;
}
// @doctest id="cb8a"

Middleware + Streaming

You can transform stream chunks in middleware before downstream consumers receive them.
$client = $client->withMiddleware($myStreamMiddleware);
// @doctest id="b2be"
Keep stream middleware focused and cheap; avoid heavy buffering unless required.

SSE Parsing with EventSourceMiddleware

use Cognesy\Http\Middleware\EventSource\EventSourceMiddleware;

$client = $client->withMiddleware(
    (new EventSourceMiddleware())
        ->withParser(static fn(string $payload): string|bool => $payload)
);
// @doctest id="057b"
withParser() receives assembled SSE data: payloads.

Operational Notes

  • Streaming is one-pass by nature at the transport layer.
  • If you need replay/caching, do it explicitly with dedicated stream cache components.
  • For mixed usage (stream() and content()), treat them as separate execution paths.
  • HttpClient::withSSEStream() is deprecated; use EventSourceMiddleware instead.
  • For curl streaming, streamHeaderTimeout controls how long to wait for response headers before throwing TimeoutException.