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
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 install
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).
// ./src/entry-server.tsx
import { renderToString } from 'react-dom/server'
import App from './App'
export function render() {
return renderToString(<App />)
}
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-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>,
)
Updating index.html
Update the index.html
file in the root of your project. The <!--app-html-->
placeholder is where the server will inject the generated HTML.
<!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 id="root"><!--app-html--></div>
<script type="module" src="/src/entry-client.tsx"></script>
</body>
</html>
Create Server
First, install the dependencies:
pnpm install -D express compression sirv tsup vite-node nodemon @types/express @types/compression
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.
// ./server/index.ts
export * from './app'
Defining Constants
The HTML_KEY
constant must match the placeholder comment in index.html
. Other constants manage environment settings.
// ./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-->`
Creating the Express Server
Set up an Express server with different configurations for development and production environments.
// ./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()
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/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)
}
})
}
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/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)
}
})
}
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:
// ./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,
},
}))
Updating tsconfig.json
Update your tsconfig.json
to include the server files and configure TypeScript appropriately:
{
"include": [
"src",
"server",
"vite.config.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.
// ./tsup.config.ts
import { defineConfig } from 'tsup'
export default defineConfig({
entry: ['server'],
outDir: 'dist/server',
target: 'node22',
format: ['cjs'],
clean: true,
minify: true,
external: ['lightningcss', 'esbuild', 'vite'],
noExternal: ['express', 'sirv', 'compression'],
})
Adding Build Scripts
{
"scripts": {
"dev": "nodemon --exec vite-node server --watch server --ext ts",
"start": "NODE_ENV=production node dist/server/index.cjs",
"build": "tsc -b && npm run build:client && npm run build:ssr && npm run build:server",
"build:client": "vite build --outDir dist/client",
"build:ssr": "vite build --outDir dist/ssr --ssr src/entry-server.tsx",
"build:server": "tsup"
}
}
Running the Application
Development: Use the following command to start the application with hot reloading:
pnpm dev
Production: Build the application and start the production server:
pnpm build && pnpm start
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.
pnpm install react-router
Adding Client-Side Routing
Wrap your application with BrowserRouter
in the client entry point to enable client-side routing.
// ./src/entry-client.tsx
import { hydrateRoot } from 'react-dom/client'
import { StrictMode } from 'react'
import { BrowserRouter } from 'react-router'
import App from './App'
import './index.css'
hydrateRoot(
document.getElementById('root')!,
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
)
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.
import { renderToString } from 'react-dom/server'
import { StaticRouter } from 'react-router'
import App from './App'
export function render(url: string) {
return renderToString(
<StaticRouter location={url}>
<App />
</StaticRouter>,
)
}
Updating Server Configurations
Update both your development and production server setups to pass the request URL to the render
function:
// ./server/dev.ts
// ./server/prod.ts
const appHtml = await render(req.url)
// Replace the placeholder with the rendered HTML
html = html.replace(HTML_KEY, appHtml)
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
//...
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:
# Build App
FROM node:22-alpine as builder
WORKDIR /app
COPY . .
RUN corepack enable && pnpm install && pnpm build
# Production
FROM node:22-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./package.json
EXPOSE 3000
CMD ["npm", "run", "start"]
Building and Running the Docker Image
docker build -t react-ssr-app .
docker run -p 3000:3000 react-ssr-app
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
- 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
Top comments (0)