Home >Web Front-end >JS Tutorial >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.
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:
The flow of your app with SSR follows these steps:
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
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.
The Node.js server will run your app and generate the HTML by rendering your React components to a string (renderToString).
pnpm install
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 />) }
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-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
The HTML_KEY constant must match the placeholder comment in index.html. Other constants manage environment settings.
// ./server/index.ts export * from './app'
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-->`
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()
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) } }) }
To follow best practices for building your application, you should exclude all unnecessary packages and include only what your application actually uses.
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) } }) }
Update your tsconfig.json to include the server files and configure TypeScript appropriately:
pnpm create vite react-ssr-app --template react-swc-ts
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
// ./src/entry-server.tsx import { renderToString } from 'react-dom/server' import App from './App' export function render() { return renderToString(<App />) }
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.
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'
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-->`
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()
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.
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" ] }
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.
This is part of my series on SSR with React. Stay tuned for more articles!
I’m always open to feedback, collaboration or discussing tech ideas — feel free to reach out!
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!