Skip to main content
Building AI-Powered SaaS Apps

Claude Streaming Works Locally but Arrives All at Once in Production: Fixing SSE Buffering Between Laravel, Nginx and Next.js

Claude tokens stream locally but arrive in one block in production? Trace buffering across Laravel, PHP, Nginx and Next.js with per-hop curl checks.

9 min
Tempo de leitura
1,666
Palavras
Publicado
Engr Mejba Ahmed

Escrito por

Engr Mejba Ahmed

Compartilhar Artigo

Claude Streaming Works Locally but Arrives All at Once in Production: Fixing SSE Buffering Between Laravel, Nginx and Next.js

Your Laravel API streams Claude tokens to a Next.js frontend, and on localhost the reply types itself out word by word. In production the same request hangs, then the whole answer lands in one block. This guide shows where that buffering can happen, gives you a minimal Laravel-to-Next.js relay that passes chunks through, and provides a per-hop check to find the layer that holds output back.

Why the reply arrives in one block: four places a stream can buffer

The Claude Messages API streams a response incrementally over server-sent events when the request sets "stream": true (Anthropic streaming docs). Between Claude and the browser, the data passes through several hops. Any one of them can collect chunks before sending them on:

  1. Laravel's response object has to write and flush each chunk as it arrives.
  2. PHP's output buffer can be enabled for all files in php.ini, either as On or as a byte size such as output_buffering=4096. The directive is always Off in PHP-CLI (PHP output control configuration).
  3. Nginx buffers proxied hops by default, because proxy_buffering defaults to on (nginx proxy module).
  4. The Next.js route handler and the browser reader can either pass the body through or wait for all of it.

The "fine locally, broken in production" pattern has a likely explanation, but confirm it with the checks at the end. A local setup often skips Nginx and may run without a php.ini output buffer. PHP-FPM behind Nginx in production adds both. For background, see LLM Streaming: Why First-Token Latency Beats Total Time.

Layers 1 and 2: Laravel and PHP must flush every chunk

The Laravel responses docs describe two stream() patterns:

  • Manual flushing. The documented loop calls ob_flush() and flush() after each chunk and sets the X-Accel-Buffering: no header.
  • A Generator closure. Laravel flushes the output buffer between yielded strings and disables Nginx output buffering for you.

For SSE, response()->eventStream() returns a text/event-stream response built from a closure that yields responses. To name an event, yield a StreamedEvent. When the stream completes, Laravel sends a final </stream> update, which you can replace through the endStreamWith argument.

The Anthropic PHP SDK exposes streaming through createStream(). The claudeTextDeltas() call in the route below is a placeholder that you implement around it, following the SDK's own documentation.

use Illuminate\Http\Request;
use Illuminate\Http\StreamedEvent;

Route::post('/chat/stream', function (Request $request) {
    $prompt = $request->string('prompt');

    return response()->eventStream(function () use ($prompt) {
        try {
            // PLACEHOLDER: wrap the Anthropic PHP SDK's createStream()
            // and yield only text_delta strings. Skip ping and unknown events.
            foreach (claudeTextDeltas($prompt) as $text) {
                yield new StreamedEvent(event: 'update', data: $text);
            }
        } catch (Throwable $e) {
            report($e);
            yield new StreamedEvent(event: 'error', data: 'stream_failed');
        }
    });
});

The Claude docs say a stream may contain ping events and that new event types may be added, so your wrapper should ignore anything it does not recognise. Errors that occur mid-stream, such as overloaded_error, do not reach SDK users as events. The SDK ends the stream and throws an error to the reading code, which is why the loop sits inside try.

The catch block is a design recommendation. After the first chunk is sent, the status code can no longer change, so the route emits a named error event for the client and then ends the stream.

Tradeoff to check. The Laravel docs say that only stream() with a Generator disables Nginx buffering. Run curl -i against the route. If X-Accel-Buffering: no is missing from the response, set the header on the returned response, or switch to stream() with a Generator and format the SSE lines yourself.

Layer 3: Nginx buffering and client aborts

The directives in this section belong to Nginx's proxy module. They govern proxy_pass hops, such as Nginx in front of Next.js, or in front of Laravel running as an HTTP app server like Octane. If Nginx reaches PHP-FPM through fastcgi_pass, a separate FastCGI module with its own buffering, timeout and client-abort directives handles that hop. Look up the equivalents in that module's documentation, because the proxy_* settings have no effect there.

On a proxied hop with buffering enabled, Nginx reads the upstream response into its buffers before passing it on. With buffering disabled, it passes the response to the client as it is received (nginx proxy module).

The upstream can set X-Accel-Buffering: no to disable buffering for a single response. However, proxy_ignore_headers can disable this capability, so search shared includes for that directive. Rely on the per-response header so that ordinary routes keep buffering. If you cannot control the header, scope proxy_buffering off to a location block that matches only the streaming path.

Two more proxy defaults matter:

  • proxy_read_timeout is 60s and applies between two successive reads. A stream that keeps sending tokens survives, but one that goes silent for 60 seconds is closed.
  • proxy_ignore_client_abort is off, so Nginx closes the upstream connection when the client disconnects. Keep it that way on streaming routes.

A typical deployment has two Nginx hops, and each one buffers independently. For base server setup, see Deploy Next.js to a VPS with Nginx: Standalone Output, systemd and No More 502s.

Two parallel pipes compare a buffered proxy hop that collects data into a tank and a streaming hop that passes data through, with a switch controlling which path is used.

Layer 4: a Next.js route handler that passes chunks through

Next.js Route Handlers can stream by returning a Web API Response whose body is a ReadableStream (Next.js route handler docs). A fetch() response body is already a stream, so the handler can return it without reading it.

// app/api/chat/route.ts
export async function POST(request: Request) {
  let upstream: Response;
  try {
    upstream = await fetch(`${process.env.LARAVEL_URL}/chat/stream`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
      body: await request.text(),
      signal: request.signal,
    });
  } catch {
    return Response.json({ error: 'upstream_unreachable' }, { status: 502 });
  }

  if (!upstream.ok || !upstream.body) {
    return Response.json(
      { error: 'upstream_failed' },
      { status: upstream.status >= 400 ? upstream.status : 502 },
    );
  }

  return new Response(upstream.body, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'X-Accel-Buffering': 'no',
    },
  });
}

The most common bug at this layer is calling await upstream.text() or await upstream.json() before responding. Either call waits for the entire stream, which recreates the one-block symptom.

Two choices in this handler are design recommendations:

  • Non-2xx responses return a JSON error instead of a failed body labelled text/event-stream.
  • request.signal is intended to cancel the upstream fetch when the browser disconnects. Whether that also stops PHP-FPM and the Claude request depends on your runtime, so verify it with the abort check below.

Keep the Claude key on the server. For related pitfalls, see Is Your OpenAI or Claude API Key in the Browser? Fixing NEXT_PUBLIC_ Leaks in AI-Built Next.js MVPs.

On the client, EventSource only issues GET requests, so it cannot call this POST route. Use fetch() with an AbortController instead:

  1. Check response.ok and the content type before reading the body.
  2. Read the body with getReader() and a streaming TextDecoder.
  3. Split the decoded text into events on blank lines and read the data: lines.
  4. Stop on an error event. On </stream>, stop and call abort().

If the Laravel route sits behind CSRF middleware, the server-to-server call from Next.js will be rejected. Register the route outside that check.

Per-hop flush checklist

These are proposed test steps. Send the same request to each hop and find the first one where spaced-out events collapse into a single burst. The -N flag disables curl's own buffering.

curl -N -i -X POST https://api.example.com/chat/stream \
  -H 'Content-Type: application/json' -d '{"prompt":"Count to twenty slowly"}'

Repeat it against these targets:

  1. Laravel directly, if it runs as an HTTP app server.
  2. Laravel through its Nginx.
  3. The Next.js /api/chat route.
  4. The browser network tab.

PHP-FPM has no HTTP port, and php artisan serve runs the CLI SAPI, where output_buffering is always Off. To check the FPM value, add a temporary route that returns ini_get('output_buffering'), request it through Nginx, and then remove the route. Any value other than 0 or empty makes the PHP buffer a suspect.

Match the first failing hop to its fix:

  • Hop 1: add a Generator or per-chunk flush.
  • Hop 2: send X-Accel-Buffering: no and check proxy_ignore_headers or the FastCGI module's equivalent.
  • Hop 3: return upstream.body without awaiting it, and set the header on that Nginx hop as well.
  • Browser only: use a reader loop instead of response.text().

For the abort check, press Ctrl+C partway through hop 2. Then watch the Laravel logs and your Claude usage to see whether generation stopped. If you move long generations into jobs, see Why Laravel Queue Workers Kill Long Claude Calls: Aligning HTTP Timeouts, Job Timeout and retry_after.

A row of four measuring stations along a stream, where the first station that shows spaced pulses merging into one burst marks the layer to fix.

FAQ

Why does it work with php artisan serve but not under PHP-FPM? The FPM php.ini may set output_buffering, and production adds an Nginx hop that buffers by default. Check the FPM value with an ini_get route, then test hop 2.

Do I need proxy_buffering off globally? No. On a proxied hop, X-Accel-Buffering: no disables buffering for that response only, unless proxy_ignore_headers lists the header.

Can I use EventSource? Not with this POST endpoint. EventSource needs a separately designed GET route.

Why does the stream cut off after about a minute? On a proxy_pass hop, proxy_read_timeout closes the connection after 60 seconds without output. A FastCGI hop has its own timeout.

Trace your stream hop by hop today

Run the curl checks, read the FPM output_buffering value, and fix only the first hop that fails. Confirm that X-Accel-Buffering: no appears on both the Laravel and Next.js responses. Return upstream.body without awaiting it, keep the JSON error path, pass request.signal upstream, and read the stream with a fetch() reader loop. Finish with the abort check so you know whether closing the tab really stops the Claude request.

Want this built into your product? See AI Integration for Laravel & WordPress — OpenAI & Claude.

Coffee cup

Gostou deste artigo?

Seu apoio me ajuda a criar mais conteúdo técnico aprofundado, ferramentas open-source e recursos gratuitos para a comunidade de desenvolvedores.

Tópicos Relacionados

Engr Mejba Ahmed

Engr Mejba Ahmed

Engr. Mejba Ahmed builds AI-powered applications and secure cloud systems for businesses worldwide. With 8+ years shipping production software in Laravel, Python, and AWS, he's helped companies automate workflows, reduce infrastructure costs, and scale without security headaches. He writes about practical AI integration, cloud architecture, and developer productivity.

Artigos Relacionados

Ver Todos

Comments

Leave a Comment

Share a question or add to the discussion.

Comments are moderated before appearing.

Learning Resources

Expand Your Knowledge

Accelerate your growth with structured courses, verified certificates, interactive flashcards, and production-ready AI agent skills.

Sample Certificate of Completion

Sample certificate — complete any course to earn yours

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by Claude

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support