React  

Exploring Real-Time Data Rendering in Next.js Using Server-Side Streaming

Introduction

Modern applications need real-time updates for dashboards, live notifications, stock prices, chats, analytics, and more. Instead of waiting for the entire page to load, server-side streaming in Next.js allows you to send UI components to the browser as they are ready. This improves speed, reduces latency, and delivers a smooth, real-time experience. In this article, we explore how streaming works in Next.js, why it matters, and how to implement it using simple examples.

What Is Server-Side Streaming?

Server-side streaming allows the server to send HTML chunks to the client gradually instead of rendering everything at once.

Key Points

  • Users see content faster

  • Improves performance for slow APIs

  • Great for dashboards and real-time data

  • Works with React Server Components

  • Reduces time-to-first-byte (TTFB)

Streaming is supported by Next.js App Router using React’s built-in streaming capabilities.

Why Use Streaming in Real-Time Applications?

Streaming enhances modern applications by:

  • Delivering partial content instantly

  • Making UI feel more responsive

  • Handling slow network/API responses gracefully

  • Reducing load on client devices

  • Improving SEO and Core Web Vitals

Example use cases:

  • Live cricket score updates in India

  • Stock price dashboards

  • Flight tracking systems

  • E-commerce order tracking

  • Real-time chat previews

How Streaming Works in Next.js

When a page loads, the server does not wait for all components to finish fetching data. Instead:

  1. The server immediately sends the static parts

  2. Slow components are rendered later

  3. Browser progressively updates the UI

This is enabled by React Suspense and Server Components.

Streaming with React Suspense in Next.js

React Suspense lets you declare parts of the UI that may take longer to load.

Example

import { Suspense } from 'react';
import LiveStats from './LiveStats';

export default function Dashboard() {
  return (
    <div>
      <h1>Real-Time Dashboard</h1>

      <Suspense fallback={<p>Loading live stats...</p>}>
        <LiveStats />
      </Suspense>
    </div>
  );
}

LiveStats is streamed as soon as it finishes loading.

Streaming Data Using Server Components

Server Components allow secure, real-time data fetching.

Example: Server Component Streaming

// LiveStats.jsx (Server Component)
export default async function LiveStats() {
  const res = await fetch('https://api.example.com/live', {
    cache: 'no-store',
  });

  const data = await res.json();

  return (
    <div>
      <h2>Current Users Online: {data.users}</h2>
    </div>
  );
}

Because this is a server component, Next.js streams the HTML as soon as data arrives.

Using Route Handlers for Streaming Responses

Next.js allows sending streaming responses using Response objects.

Example: Streaming API Route

// app/api/stream/route.js
export async function GET() {
  const encoder = new TextEncoder();

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

      const interval = setInterval(() => {
        controller.enqueue(encoder.encode(`data: ${count++}\n\n`));
        if (count > 5) {
          clearInterval(interval);
          controller.close();
        }
      }, 1000);
    },
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
    },
  });
}

This streams data every second.

Consuming Streamed Data on Client Side

'use client';
import { useEffect, useState } from 'react';

export default function StreamViewer() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const eventSource = new EventSource('/api/stream');

    eventSource.onmessage = (event) => {
      setMessages((prev) => [...prev, event.data]);
    };

    return () => eventSource.close();
  }, []);

  return (
    <div>
      <h2>Live Stream Updates</h2>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
    </div>
  );
}

This shows real-time updates as they stream from the server.

Benefits of Server-Side Streaming

1. Faster Page Loads

Users see content immediately.

2. Better Performance on Slow Networks

Streaming reduces perception of delay.

3. Improved SEO

Google receives rendered content quicker.

4. Great for Real-Time Applications

Live dashboards, news tickers, analytics.

5. Reduced Load on Client

Server handles heavy work.

Real-Life Example

A financial analytics platform in India displays real-time stock updates. Using Next.js streaming:

  • Server fetches live stock prices every second

  • UI updates continuously without full reload

  • Users experience instant updates with minimal lag

Best Practices

  • Use Suspense boundaries for slow components

  • Cache wisely (use no-store for real-time data)

  • Keep stream chunks small

  • Close streams properly to avoid memory leaks

  • Use server components for secure data fetching

Summary

Server-side streaming in Next.js allows building fast and interactive real-time applications. By using React Suspense, Server Components, and streaming APIs, developers can deliver dynamic content instantly, improve performance, and create engaging user experiences. With proper optimization and best practices, streaming becomes a powerful tool for modern apps.