search
HomeWeb Front-endJS TutorialAdvanced React SSR Techniques with Streaming and Dynamic Data

Advanced React SSR Techniques with Streaming and Dynamic Data

As your application grows, so do the challenges. To stay ahead, mastering advanced SSR techniques is essential for delivering a seamless and high-performance user experience.

Having built a foundation for server-side rendering in React projects in the previous article, I am excited to share features that can help you maintain project scalability, efficiently load data from the server to the client and resolve hydration issues.

Table of Contents

  • What is Streaming in SSR
  • Lazy Loading and SSR
  • Implementing Streaming with Lazy Loading
    • Updating React Components
    • Updating the Server for Streaming
  • Server-to-Client Data
    • Passing Data on the Server
    • Handle Environment Variables on the Client
  • Hydration Issues
    • Example Scenario
    • Fixing Hydration Issues
  • Conclusion

What is Streaming in SSR

Streaming in server-side rendering (SSR) is a technique where the server sends parts of the HTML page to the browser in chunks as they are generated, rather than waiting for the entire page to be ready before delivering it. This allows the browser to start rendering content immediately, improving load times and the user's performance.

Streaming is particularly effective for:

  • Large Pages: Where generating the entire HTML could take significant time.
  • Dynamic Content: When parts of the page depend on external API calls or dynamically generated chunks.
  • High-Traffic Applications: To reduce server load and latency during peak usage.

Streaming bridges the gap between traditional SSR and modern client-side interactivity, ensuring users see meaningful content faster without compromising on performance.

Lazy Loading and SSR

Lazy loading is a technique that defers the loading of components or modules until they are actually needed, reducing the initial load time and improving performance. When combined with SSR, lazy loading can significantly optimize both server and client workloads.

Lazy loading relies on React.lazy, which dynamically imports components as Promises. In traditional SSR, rendering is synchronous, meaning the server must resolve all Promises before generating and sending the complete HTML to the browser.

Streaming resolves these challenges by allowing the server to send HTML in chunks as components are rendered. This approach enables the Suspense fallback to be sent to the browser immediately, ensuring users see meaningful content early. As lazy-loaded components are resolved, their rendered HTML is streamed incrementally to the browser, seamlessly replacing the fallback content. This avoids blocking the rendering process, reduces delays and improves perceived load times.

Implementing Streaming with Lazy Loading

This guide builds upon concepts introduced in the previous article, Building Production-Ready SSR React Applications, which you can find linked at the bottom. To enable SSR with React and support lazy-loaded components, we’ll make several updates to both the React components and the server.

Updating React Components

Server Entry Point

React’s renderToString method is commonly used for SSR, but it waits until the entire HTML content is ready before sending it to the browser. By switching to renderToPipeableStream, we can enable streaming, which sends parts of the HTML as they are generated.

// ./src/entry-server.tsx
import { renderToPipeableStream, RenderToPipeableStreamOptions } from 'react-dom/server'
import App from './App'

export function render(options?: RenderToPipeableStreamOptions) {
  return renderToPipeableStream(<app></app>, options)
}

Creating Lazy-Loaded Component

In this example, we’ll create a simple Card component to demonstrate the concept. In production applications, this technique is typically used with larger modules or entire pages to optimize performance.

// ./src/Card.tsx
import { useState } from 'react'

function Card() {
  const [count, setCount] = useState(0)

  return (
    <div classname="card">
      <button onclick="{()"> setCount((count) => count + 1)}>
        count is {count}
      </button>
      <p>
        Edit <code>src/App.tsx</code> and save to test HMR
      </p>
    </div>
  )
}

export default Card

Using the Lazy-Loaded Component in the App

To use the lazy-loaded component, import it dynamically using React.lazy and wrap it with Suspense to provide a fallback UI during loading

// ./src/App.tsx
import { lazy, Suspense } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

const Card = lazy(() => import('./Card'))

function App() {
  return (
    
      <div>
        <a href="https://vite.dev" target="_blank">
          <img src="%7BviteLogo%7D" classname="logo" alt="Vite logo">
        </a>
        <a href="https://react.dev" target="_blank">
          <img src="%7BreactLogo%7D" classname="logo react" alt="React logo">
        </a>
      </div>
      <h1 id="Vite-React">Vite + React</h1>
      <suspense fallback="Loading...">
        <card></card>
      </suspense>
      <p classname="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    >
  )
}

export default App

Updating the Server for Streaming

To enable streaming, both the development and production setups need to support a consistent HTML rendering process. Since the process is the same for both environments, you can create a single reusable function to handle streaming content effectively.

Creating a Stream Content Function

// ./server/constants.ts
export const ABORT_DELAY = 5000

The streamContent function initiates the rendering process, writes incremental chunks of HTML to the response, and ensures proper error handling.

// ./server/streamContent.ts
import { Transform } from 'node:stream'
import { Request, Response, NextFunction } from 'express'
import { ABORT_DELAY, HTML_KEY } from './constants'
import type { render } from '../src/entry-server'

export type StreamContentArgs = {
  render: typeof render
  html: string
  req: Request
  res: Response
  next: NextFunction
}

export function streamContent({ render, html, res }: StreamContentArgs) {
  let renderFailed = false

  // Initiates the streaming process by calling the render function
  const { pipe, abort } = render({
    // Handles errors that occur before the shell is ready
    onShellError() {
      res.status(500).set({ 'Content-Type': 'text/html' }).send('<pre class="brush:php;toolbar:false">Something went wrong
') }, // Called when the shell (initial HTML) is ready for streaming onShellReady() { res.status(renderFailed ? 500 : 200).set({ 'Content-Type': 'text/html' }) // Split the HTML into two parts using the placeholder const [htmlStart, htmlEnd] = html.split(HTML_KEY) // Write the starting part of the HTML to the response res.write(htmlStart) // Create a transform stream to handle the chunks of HTML from the renderer const transformStream = new Transform({ transform(chunk, encoding, callback) { // Write each chunk to the response res.write(chunk, encoding) callback() }, }) // When the streaming is finished, write the closing part of the HTML transformStream.on('finish', () => { res.end(htmlEnd) }) // Pipe the render output through the transform stream pipe(transformStream) }, onError(error) { // Logs errors encountered during rendering renderFailed = true console.error((error as Error).stack) }, }) // Abort the rendering process after a delay to avoid hanging requests setTimeout(abort, ABORT_DELAY) }

Updating Development Configuration

// ./server/dev.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import { StreamContentArgs } from './streamContent'

const HTML_PATH = path.resolve(process.cwd(), 'index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'src/entry-server.tsx')

// Add to args the streamContent callback
export async function setupDev(app: Application, streamContent: (args: StreamContentArgs) => void) {
  const vite = await (
    await import('vite')
  ).createServer({
    root: process.cwd(),
    server: { middlewareMode: true },
    appType: 'custom',
  })

  app.use(vite.middlewares)

  app.get('*', async (req, res, next) => {
    try {
      let html = fs.readFileSync(HTML_PATH, 'utf-8')
      html = await vite.transformIndexHtml(req.originalUrl, html)

      const { render } = await vite.ssrLoadModule(ENTRY_SERVER_PATH)

      // Use the same callback for production and development process
      streamContent({ render, html, req, res, next })
    } catch (e) {
      vite.ssrFixStacktrace(e as Error)
      console.error((e as Error).stack)
      next(e)
    }
  })
}

Updating Production Configuration

// ./server/prod.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import compression from 'compression'
import sirv from 'sirv'
import { StreamContentArgs } from './streamContent'

const CLIENT_PATH = path.resolve(process.cwd(), 'dist/client')
const HTML_PATH = path.resolve(process.cwd(), 'dist/client/index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'dist/ssr/entry-server.js')

// Add to Args the streamContent callback
export async function setupProd(app: Application, streamContent: (args: StreamContentArgs) => void) {
  app.use(compression())
  app.use(sirv(CLIENT_PATH, { extensions: [] }))

  app.get('*', async (req, res, next) => {
    try {
      const html = fs.readFileSync(HTML_PATH, 'utf-8')

      const { render } = await import(ENTRY_SERVER_PATH)

      // Use the same callback for production and development process
      streamContent({ render, html, req, res, next })
    } catch (e) {
      console.error((e as Error).stack)
      next(e)
    }
  })
}

Updating the Express Server

Pass the streamContent function to each configuration:

// ./server/app.ts
import express from 'express'
import { PROD, APP_PORT } from './constants'
import { setupProd } from './prod'
import { setupDev } from './dev'
import { streamContent } from './streamContent'

export async function createServer() {
  const app = express()

  if (PROD) {
    await setupProd(app, streamContent)
  } else {
    await setupDev(app, streamContent)
  }

  app.listen(APP_PORT, () => {
    console.log(`http://localhost:${APP_PORT}`)
  })
}

createServer()

After implementing these changes, your server will:

  • Stream HTML to the browser incrementally, reducing time to first paint.
  • Seamlessly handle lazy-loaded components, improving both performance and user experience.

Server-to-Client Data

Before sending HTML to the client, you have full control over the server-generated HTML. This allows you to dynamically modify the structure by adding tags, styles, links or any other elements as needed.

One particularly powerful technique is injecting a <script> tag into the HTML. This approach enables you to pass dynamic data directly to the client.</script>

In this example, we’ll focus on passing an environment variable, but you can pass any JavaScript object you need. By passing environment variables to the client, you avoid rebuilding the entire application when those variables change. In the example repository linked at the bottom, you can also see how profile data is passed dynamically.

Passing Data on the Server

Define API_URL

Set an API_URL environment variable on the server. By default, this will point to jsonplaceholder. The __INITIAL_DATA__ will act as the key for storing data on the global window object.

// ./src/entry-server.tsx
import { renderToPipeableStream, RenderToPipeableStreamOptions } from 'react-dom/server'
import App from './App'

export function render(options?: RenderToPipeableStreamOptions) {
  return renderToPipeableStream(<app></app>, options)
}

Inject Initial Data into HTML

Create a utility function to inject the initial data into the HTML string before sending it to the client. This data will include environment variables like API_URL.

// ./src/Card.tsx
import { useState } from 'react'

function Card() {
  const [count, setCount] = useState(0)

  return (
    <div classname="card">
      <button onclick="{()"> setCount((count) => count + 1)}>
        count is {count}
      </button>
      <p>
        Edit <code>src/App.tsx</code> and save to test HMR
      </p>
    </div>
  )
}

export default Card

Update streamContent

Use the applyInitialData function to inject the initial data into the HTML and send it to the client.

// ./src/App.tsx
import { lazy, Suspense } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

const Card = lazy(() => import('./Card'))

function App() {
  return (
    
      <div>
        <a href="https://vite.dev" target="_blank">
          <img src="%7BviteLogo%7D" classname="logo" alt="Vite logo">
        </a>
        <a href="https://react.dev" target="_blank">
          <img src="%7BreactLogo%7D" classname="logo react" alt="React logo">
        </a>
      </div>
      <h1 id="Vite-React">Vite + React</h1>
      <suspense fallback="Loading...">
        <card></card>
      </suspense>
      <p classname="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    >
  )
}

export default App

Handle Environment Variables on the Client

Extend the Global window Type

Update the global type declaration to include the __INITIAL_DATA__ key and its structure.

// ./server/constants.ts
export const ABORT_DELAY = 5000

Access API_URL from the Window Object

// ./server/streamContent.ts
import { Transform } from 'node:stream'
import { Request, Response, NextFunction } from 'express'
import { ABORT_DELAY, HTML_KEY } from './constants'
import type { render } from '../src/entry-server'

export type StreamContentArgs = {
  render: typeof render
  html: string
  req: Request
  res: Response
  next: NextFunction
}

export function streamContent({ render, html, res }: StreamContentArgs) {
  let renderFailed = false

  // Initiates the streaming process by calling the render function
  const { pipe, abort } = render({
    // Handles errors that occur before the shell is ready
    onShellError() {
      res.status(500).set({ 'Content-Type': 'text/html' }).send('<pre class="brush:php;toolbar:false">Something went wrong
') }, // Called when the shell (initial HTML) is ready for streaming onShellReady() { res.status(renderFailed ? 500 : 200).set({ 'Content-Type': 'text/html' }) // Split the HTML into two parts using the placeholder const [htmlStart, htmlEnd] = html.split(HTML_KEY) // Write the starting part of the HTML to the response res.write(htmlStart) // Create a transform stream to handle the chunks of HTML from the renderer const transformStream = new Transform({ transform(chunk, encoding, callback) { // Write each chunk to the response res.write(chunk, encoding) callback() }, }) // When the streaming is finished, write the closing part of the HTML transformStream.on('finish', () => { res.end(htmlEnd) }) // Pipe the render output through the transform stream pipe(transformStream) }, onError(error) { // Logs errors encountered during rendering renderFailed = true console.error((error as Error).stack) }, }) // Abort the rendering process after a delay to avoid hanging requests setTimeout(abort, ABORT_DELAY) }

Make a Request Using the Dynamic API_URL

// ./server/dev.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import { StreamContentArgs } from './streamContent'

const HTML_PATH = path.resolve(process.cwd(), 'index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'src/entry-server.tsx')

// Add to args the streamContent callback
export async function setupDev(app: Application, streamContent: (args: StreamContentArgs) => void) {
  const vite = await (
    await import('vite')
  ).createServer({
    root: process.cwd(),
    server: { middlewareMode: true },
    appType: 'custom',
  })

  app.use(vite.middlewares)

  app.get('*', async (req, res, next) => {
    try {
      let html = fs.readFileSync(HTML_PATH, 'utf-8')
      html = await vite.transformIndexHtml(req.originalUrl, html)

      const { render } = await vite.ssrLoadModule(ENTRY_SERVER_PATH)

      // Use the same callback for production and development process
      streamContent({ render, html, req, res, next })
    } catch (e) {
      vite.ssrFixStacktrace(e as Error)
      console.error((e as Error).stack)
      next(e)
    }
  })
}

Now you have a dynamic environment variable available in your client-side code, enabling you to manage server-to-client data without the need to rebuild the JavaScript bundle. This approach simplifies configuration and makes your app more flexible and scalable.

Hydration Issues

Now that you can pass data from the server to the client, you might encounter hydration issues if you try to use this data directly inside a component. These errors occur because the server-rendered HTML doesn’t match the initial React render on the client.

Example Scenario

Consider using API_URL as a simple string in your component

// ./src/entry-server.tsx
import { renderToPipeableStream, RenderToPipeableStreamOptions } from 'react-dom/server'
import App from './App'

export function render(options?: RenderToPipeableStreamOptions) {
  return renderToPipeableStream(<app></app>, options)
}

In this case, the server will render the component with API_URL as an empty string, but on the client, API_URL will already have a value from the window object. This mismatch causes a hydration error because React detects a difference between the server-rendered HTML and the client’s React tree.

While the user may see the content update quickly, React logs a hydration warning in the console. To fix this issue, you need to ensure that the server and client render the same initial HTML or pass API_URL explicitly to the server entry point.

Fixing Hydration Issues

To resolve error, pass initialData to the App component via the server entry point.

Update streamContent

// ./src/Card.tsx
import { useState } from 'react'

function Card() {
  const [count, setCount] = useState(0)

  return (
    <div classname="card">
      <button onclick="{()"> setCount((count) => count + 1)}>
        count is {count}
      </button>
      <p>
        Edit <code>src/App.tsx</code> and save to test HMR
      </p>
    </div>
  )
}

export default Card

Handle Data in the render Function

// ./src/App.tsx
import { lazy, Suspense } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

const Card = lazy(() => import('./Card'))

function App() {
  return (
    
      <div>
        <a href="https://vite.dev" target="_blank">
          <img src="%7BviteLogo%7D" classname="logo" alt="Vite logo">
        </a>
        <a href="https://react.dev" target="_blank">
          <img src="%7BreactLogo%7D" classname="logo react" alt="React logo">
        </a>
      </div>
      <h1 id="Vite-React">Vite + React</h1>
      <suspense fallback="Loading...">
        <card></card>
      </suspense>
      <p classname="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    >
  )
}

export default App

Use initialData in the App Component

// ./server/constants.ts
export const ABORT_DELAY = 5000

Now, your server-rendered HTML will match the initial React render on the client, eliminating hydration errors. React will correctly reconcile the server and client trees, ensuring a seamless experience.

For dynamic data like API_URL, consider using React Context to manage and pass default values between the server and client. This approach simplifies managing shared data across components. You can find an example implementation in the linked repository at the bottom.

Conclusion

In this article, we explored advanced SSR techniques for React, focusing on implementing streaming, managing server-to-client data and resolving hydration issues. These methods ensure your application is scalable, high-performing and create seamless user experiences.

Explore the Code

  • Example: react-ssr-advanced-example
  • Template: react-ssr-streaming-template
  • Vite Extra Template: template-ssr-react-streaming-ts

Related Articles

This is part of my series on SSR with React. Stay tuned for more articles!

  • Building Production-Ready SSR React Applications
  • Advanced React SSR Techniques with Streaming and Dynamic Data (You are here)
  • Setting Up Themes in SSR React Applications (Coming soon)

Stay Connected

I’m always open to feedback, collaboration or discussing tech ideas — feel free to reach out!

  • Portfolio: maxh1t.xyz
  • Email: m4xh17@gmail.com

The above is the detailed content of Advanced React SSR Techniques with Streaming and Dynamic Data. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.