Building Production-Ready SSR React Applications
In a world where every millisecond matters, server-side rendering has become an essential capability for frontend applications.
This guide will walk you through the fundamental patterns for building a production-ready SSR with React. You'll gain an understanding of the principles behind React-based frameworks with built-in SSR (like Next.js) and learn how to create your own custom solutions.
The provided code is production-ready, featuring a complete build process for both client and server parts, including a Dockerfile. In this implementation, Vite is used to build the client and SSR code, but you can use any other tools of your choice. Vite is also give hot-reloading during development mode for the client.
If you're interested in a version of this setup without Vite, feel free to reach out.
Table of Contents
- What is SSR
-
Creating the App
- Initializing Vite
- Updating React Components
- Create Server
- Configuring the Build
- Routing
- Docker
- Conclusion
What is SSR
Server-side rendering (SSR) is a technique in web development where the server generates the HTML content of a web page before sending it to the browser. Unlike traditional client-side rendering (CSR), where JavaScript builds the content on the user's device after loading an empty HTML shell, SSR delivers fully-rendered HTML right from the server.
Key benefits of SSR:
- Improved SEO: Since search engine crawlers receive fully-rendered content, SSR ensures better indexing and ranking.
- Faster First Paint: Users see meaningful content almost immediately, as the server handles the heavy lifting of rendering.
- Enhanced Performance: By reducing the rendering workload on the browser, SSR provides a smoother experience for users on older or less powerful devices.
- Seamless Server-to-Client Data Transfer: SSR allows you to pass dynamic server-side data to the client without rebuilding the client bundle.
Creating The App
The flow of your app with SSR follows these steps:
- Read the template HTML file.
- Initialize React and generate an HTML string of the app's content.
- Inject the generated HTML string into the template.
- Send the complete HTML to the browser.
- On the client, match the HTML tags and hydrate the application, making it interactive.
Initializing Vite
I prefer to use pnpm and react-swc-ts Vite template, but you can choose any other setup.
pnpm create vite react-ssr-app --template react-swc-ts
Install the dependencies:
pnpm create vite react-ssr-app --template react-swc-ts
Updating React Components
In a typical React application, there’s a single main.tsx entry point for index.html. With SSR, you need two entry points: one for the server and one for the client.
Server Entry Point
The Node.js server will run your app and generate the HTML by rendering your React components to a string (renderToString).
pnpm install
Client Entry Point
The browser will hydrate the server-generated HTML, connecting it with the JavaScript to make the page interactive.
Hydration is the process of attaching event listeners and other dynamic behaviors to the static HTML rendered by the server.
// ./src/entry-server.tsx import { renderToString } from 'react-dom/server' import App from './App' export function render() { return renderToString(<App />) }
Updating index.html
Update the index.html file in the root of your project. The placeholder is where the server will inject the generated HTML.
// ./src/entry-client.tsx import { hydrateRoot } from 'react-dom/client' import { StrictMode } from 'react' import App from './App' import './index.css' hydrateRoot( document.getElementById('root')!, <StrictMode> <App /> </StrictMode>, )
All dependencies required for the server should be installed as development dependencies (devDependencies) to ensure they are not included in the client bundle.
Next, create a folder in the root of your project named ./server and add the following files.
Re-exporting the Main Server File
Re-export the main server file. This makes running commands more convenient.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React + TS</title> </head> <body> <div> <h3> Create Server </h3> <p>First, install the dependencies:<br> </p> <pre class="brush:php;toolbar:false">pnpm install -D express compression sirv tsup vite-node nodemon @types/express @types/compression
Defining Constants
The HTML_KEY constant must match the placeholder comment in index.html. Other constants manage environment settings.
// ./server/index.ts export * from './app'
Creating the Express Server
Set up an Express server with different configurations for development and production environments.
// ./server/constants.ts export const NODE_ENV = process.env.NODE_ENV || 'development' export const APP_PORT = process.env.APP_PORT || 3000 export const PROD = NODE_ENV === 'production' export const HTML_KEY = `<!--app-html-->`
Development Mode Configuration
In development, use Vite’s middleware to handle requests and dynamically transform the index.html file with hot reload. The server will load the React application and render it to HTML on each request.
// ./server/app.ts import express from 'express' import { PROD, APP_PORT } from './constants' import { setupProd } from './prod' import { setupDev } from './dev' export async function createServer() { const app = express() if (PROD) { await setupProd(app) } else { await setupDev(app) } app.listen(APP_PORT, () => { console.log(`http://localhost:${APP_PORT}`) }) } createServer()
Production Mode Configuration
In production, use compression to optimize performance, sirv to serve static files and the pre-built server bundle to render the app.
// ./server/dev.ts import { Application } from 'express' import fs from 'fs' import path from 'path' import { HTML_KEY } from './constants' const HTML_PATH = path.resolve(process.cwd(), 'index.html') const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'src/entry-server.tsx') export async function setupDev(app: Application) { // Create a Vite development server in middleware mode const vite = await ( await import('vite') ).createServer({ root: process.cwd(), server: { middlewareMode: true }, appType: 'custom', }) // Use Vite middleware for serving files app.use(vite.middlewares) app.get('*', async (req, res, next) => { try { // Read and transform the HTML file let html = fs.readFileSync(HTML_PATH, 'utf-8') html = await vite.transformIndexHtml(req.originalUrl, html) // Load the entry-server.tsx module and render the app const { render } = await vite.ssrLoadModule(ENTRY_SERVER_PATH) const appHtml = await render() // Replace the placeholder with the rendered HTML html = html.replace(HTML_KEY, appHtml) res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (e) { // Fix stack traces for Vite and handle errors vite.ssrFixStacktrace(e as Error) console.error((e as Error).stack) next(e) } }) }
Configuring the Build
To follow best practices for building your application, you should exclude all unnecessary packages and include only what your application actually uses.
Updating Vite Configuration
Update your Vite configuration to optimize the build process and handle SSR dependencies:
// ./server/prod.ts import { Application } from 'express' import fs from 'fs' import path from 'path' import compression from 'compression' import sirv from 'sirv' import { HTML_KEY } from './constants' 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') export async function setupProd(app: Application) { // Use compression for responses app.use(compression()) // Serve static files from the client build folder app.use(sirv(CLIENT_PATH, { extensions: [] })) app.get('*', async (_, res, next) => { try { // Read the pre-built HTML file let html = fs.readFileSync(HTML_PATH, 'utf-8') // Import the server-side render function and generate HTML const { render } = await import(ENTRY_SERVER_PATH) const appHtml = await render() // Replace the placeholder with the rendered HTML html = html.replace(HTML_KEY, appHtml) res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (e) { // Log errors and pass them to the error handler console.error((e as Error).stack) next(e) } }) }
Updating tsconfig.json
Update your tsconfig.json to include the server files and configure TypeScript appropriately:
pnpm create vite react-ssr-app --template react-swc-ts
Creating tsup Configuration
Use tsup, a TypeScript bundler, to build the server code. The noExternal option specifies the packages to bundle with the server. Be sure to include any additional packages your server uses.
pnpm install
Adding Build Scripts
// ./src/entry-server.tsx import { renderToString } from 'react-dom/server' import App from './App' export function render() { return renderToString(<App />) }
Running the Application
Development: Use the following command to start the application with hot reloading:
// ./src/entry-client.tsx import { hydrateRoot } from 'react-dom/client' import { StrictMode } from 'react' import App from './App' import './index.css' hydrateRoot( document.getElementById('root')!, <StrictMode> <App /> </StrictMode>, )
Production: Build the application and start the production server:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React + TS</title> </head> <body> <div> <h3> Create Server </h3> <p>First, install the dependencies:<br> </p> <pre class="brush:php;toolbar:false">pnpm install -D express compression sirv tsup vite-node nodemon @types/express @types/compression
To verify that SSR is working, check the first network request to your server. The response should contain the fully-rendered HTML of your application.
Routing
To add different pages to your app, you need to configure routing properly and handle it in both client and server entry points.
// ./server/index.ts export * from './app'
Adding Client-Side Routing
Wrap your application with BrowserRouter in the client entry point to enable client-side routing.
// ./server/constants.ts export const NODE_ENV = process.env.NODE_ENV || 'development' export const APP_PORT = process.env.APP_PORT || 3000 export const PROD = NODE_ENV === 'production' export const HTML_KEY = `<!--app-html-->`
Adding Server-Side Routing
Use StaticRouter in the server entry point to handle server-side routing. Pass the url as a prop to render the correct route based on the request.
// ./server/app.ts import express from 'express' import { PROD, APP_PORT } from './constants' import { setupProd } from './prod' import { setupDev } from './dev' export async function createServer() { const app = express() if (PROD) { await setupProd(app) } else { await setupDev(app) } app.listen(APP_PORT, () => { console.log(`http://localhost:${APP_PORT}`) }) } createServer()
Updating Server Configurations
Update both your development and production server setups to pass the request URL to the render function:
// ./server/dev.ts import { Application } from 'express' import fs from 'fs' import path from 'path' import { HTML_KEY } from './constants' const HTML_PATH = path.resolve(process.cwd(), 'index.html') const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'src/entry-server.tsx') export async function setupDev(app: Application) { // Create a Vite development server in middleware mode const vite = await ( await import('vite') ).createServer({ root: process.cwd(), server: { middlewareMode: true }, appType: 'custom', }) // Use Vite middleware for serving files app.use(vite.middlewares) app.get('*', async (req, res, next) => { try { // Read and transform the HTML file let html = fs.readFileSync(HTML_PATH, 'utf-8') html = await vite.transformIndexHtml(req.originalUrl, html) // Load the entry-server.tsx module and render the app const { render } = await vite.ssrLoadModule(ENTRY_SERVER_PATH) const appHtml = await render() // Replace the placeholder with the rendered HTML html = html.replace(HTML_KEY, appHtml) res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (e) { // Fix stack traces for Vite and handle errors vite.ssrFixStacktrace(e as Error) console.error((e as Error).stack) next(e) } }) }
With these changes, you can now create routes in your React app that are fully compatible with SSR. However, this basic approach does not handle lazy-loaded components (React.lazy). For managing lazy-loaded modules, please refer to my other article, Advanced React SSR Techniques with Streaming and Dynamic Data, linked at the bottom.
Docker
Here’s a Dockerfile to containerize your application:
// ./server/prod.ts import { Application } from 'express' import fs from 'fs' import path from 'path' import compression from 'compression' import sirv from 'sirv' import { HTML_KEY } from './constants' 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') export async function setupProd(app: Application) { // Use compression for responses app.use(compression()) // Serve static files from the client build folder app.use(sirv(CLIENT_PATH, { extensions: [] })) app.get('*', async (_, res, next) => { try { // Read the pre-built HTML file let html = fs.readFileSync(HTML_PATH, 'utf-8') // Import the server-side render function and generate HTML const { render } = await import(ENTRY_SERVER_PATH) const appHtml = await render() // Replace the placeholder with the rendered HTML html = html.replace(HTML_KEY, appHtml) res.status(200).set({ 'Content-Type': 'text/html' }).end(html) } catch (e) { // Log errors and pass them to the error handler console.error((e as Error).stack) next(e) } }) }
Building and Running the Docker Image
// ./vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react-swc' import { dependencies } from './package.json' export default defineConfig(({ mode }) => ({ plugins: [react()], ssr: { noExternal: mode === 'production' ? Object.keys(dependencies) : undefined, }, }))
{ "include": [ "src", "server", "vite.config.ts" ] }
Conclusion
In this guide, we’ve established a strong foundation for creating production-ready SSR applications with React. You’ve learned how to set up the project, configure routing and create a Dockerfile. This setup is ideal for building landing pages or small app efficiently.
Explore the Code
- Example: react-ssr-basics-example
- Template: react-ssr-template
- Vite Extra Template: template-ssr-react-ts
Related Articles
This is part of my series on SSR with React. Stay tuned for more articles!
- Building Production-Ready SSR React Applications (You are here)
- Advanced React SSR Techniques with Streaming and Dynamic Data (Coming soon)
- 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 Building Production-Ready SSR React Applications. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
