search
HomeWeb Front-endJS TutorialBuilding Production-Ready SSR React Applications

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:

  1. Read the template HTML file.
  2. Initialize React and generate an HTML string of the app's content.
  3. Inject the generated HTML string into the template.
  4. Send the complete HTML to the browser.
  5. 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></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></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.


  
    <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>
  
  
    <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></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></app>
  </strictmode>,
)

Production: Build the application and start the production server:


  
    <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>
  
  
    <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!

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
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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.