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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

Zend Studio 13.0.1
Powerful PHP integrated development environment
