Tech Verse Logo
Enable dark mode
Next.js Route Handler Streaming with ReadableStream

Next.js Route Handler Streaming with ReadableStream

Md. Mostafijur Rahman
•4 min read

Waiting for a large payload to assemble in memory before returning an HTTP response will hurt your latency metrics. Next.js route handler streaming lets you pipe data chunks to the client the moment they become available. You don't have to wait for an entire database cursor to exhaust or an external API to finish its cycle. You can construct a native ReadableStream and return it inside a standard Response object.

Standard web APIs make this straightforward. The ReadableStream constructor accepts an underlying source object with a start method. This method receives a controller you use to enqueue chunks and eventually close the stream. If you need to stop sending data due to an error, you throw inside the controller or simply invoke the close method when your generator finishes its work. For background reading on how Next.js handles network boundaries, you might want to look at Mastering Next.js Streaming and Suspense.

Memory consumption scales linearly when you buffer entire payloads. Don't do it. Stream them instead. It's faster. Users hate staring at blank white screens while an upstream service aggregates gigabytes of data. Let's fix that.

Building a Basic Text Streamer

Let's write a route handler that pushes incremental strings down the wire every few hundred milliseconds. This setup mimics a slow data source or an asynchronous queue consumer. You'll define an app/api/stream/route.ts file that exports a GET method. Inside that method, instantiate your stream and pass a custom transformer.

import { NextResponse } from "next/server";

export async function GET() {
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    start(controller) {
      let counter = 0;

      const interval = setInterval(() => {
        if (counter > 5) {
          clearInterval(interval);
          controller.close();
          return;
        }

        const data = JSON.stringify({ count: counter, timestamp: Date.now() });
        controller.enqueue(encoder.encode(data + "\n"));
        counter++;
      }, 300);
    },
  });

  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache, no-transform",
      "Connection": "keep-alive",
    },
  });
}

That route uses Server-Sent Events headers to keep the connection alive. Notice how we encode every string chunk into a Uint8Array using TextEncoder. If you forget to encode your strings, the underlying stream throws a type error because it expects binary data chunks. The connection headers prevent intermediate proxies from buffering the output, which is a common gotcha when deploying behind Nginx or Varnish.

Colleagues often ask why we don't just use WebSockets here. WebSockets introduce stateful connection management overhead on serverless targets. Route handlers are stateless. They spin up, stream, and die. It's clean.

Handling Client Disconnections

Clients close browser tabs or navigate away before a stream finishes. If your route handler keeps querying a database or an external microservice after the client disconnects, you waste compute resources. The ReadableStream controller provides a cancellation hook via the cancel method on your underlying source. You can listen for aborted requests and clean up active timers or database handles.

export async function GET(request: Request) {
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    start(controller) {
      const timer = setInterval(() => {
        if (request.signal.aborted) {
          clearInterval(timer);
          return;
        }

        controller.enqueue(encoder.encode("ping\n"));
      }, 1000);

      request.signal.addEventListener("abort", () => {
        clearInterval(timer);
        controller.close();
      });
    },
  });

  return new Response(stream);
}

We check the request.signal.aborted boolean and attach an event listener to the abort signal. This guarantees that background intervals terminate immediately when the TCP socket drops. Without this cleanup, lingering timers can exhaust your Node.js event loop capacity under high traffic loads. If you are dealing with resource limits during heavy operations, review Fixing Node.js Memory Limits in Next.js Builds for complementary memory management strategies.

Timeouts will bite you if you don't account for idle connections. Proxies drop quiet sockets after sixty seconds. Send periodic heartbeats or keepalive tokens. Your infrastructure will thank you.

Consuming the Stream on the Client

Reading a streamed response on the client requires parsing the body as a stream reader. You fetch the route endpoint as normal, but instead of calling res.json(), you access res.body.getReader(). You loop over the chunks using a while loop until the reader reports that the stream is done.

"use client"

import { useState, useEffect } from "react";

export default function StreamViewer() {
  const [logs, setLogs] = useState<string[]>([]);

  useEffect(() => {
    async function fetchStream() {
      const response = await fetch("/api/stream");
      if (!response.body) return;

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        setLogs((prev) => [...prev, chunk]);
      }
    }

    fetchStream();
  }, []);

  return (
    <div>
      {logs.map((log, index) => (
        <p key={index}>{log}</p>
      ))}
    </div>
  );
}

The { stream: true } option passed to the text decoder tells it to handle multi-byte characters that might be split across two separate chunk boundaries. If you omit that option, characters split across chunks will render replacement characters in the user interface. Keep your chunk sizes uniform and test your client-side reader with simulated network throttling to catch buffering issues early.

You'll find that error handling inside the reader loop requires explicit try-catch blocks around the read invocation. Network drops throw standard DOM exceptions. Catch them, update your UI state to show a disconnected badge, and stop the spinner. Don't leave the UI hanging in an indeterminate state.

Scaling these streams in production requires you to consider proxy configurations, idle timeout values, and load balancer buffering limits. Nginx, for instance, buffers upstream responses by default unless you explicitly disable buffering via proxy headers. Make sure your server infrastructure is tuned correctly before pushing high-throughput chunked responses to real users. Testing with artillery or k6 helps identify bottlenecks under heavy concurrent load.

    Latest Posts

    View All

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    Managing Shared Layout State in Next.js App Router

    Managing Shared Layout State in Next.js App Router

    Hardening Systemd Services Against Attacks

    Hardening Systemd Services Against Attacks

    Profiling and Fixing Python Memory Leaks

    Profiling and Fixing Python Memory Leaks

    Building Accessible Comboboxes with React Aria and Tailwind

    Building Accessible Comboboxes with React Aria and Tailwind

    Scaling Python Monorepos with UV Workspaces

    Scaling Python Monorepos with UV Workspaces

    Fixing Node.js Memory Limits in Next.js Builds

    Fixing Node.js Memory Limits in Next.js Builds