Server Rendering
React Router Framework Mode includes built-in server-side rendering (SSR) support through the Vite plugin.Overview
SSR is enabled by default in Framework Mode. The Vite plugin handles:- Rendering React components to HTML on the server
- Loading data via route
loaderfunctions before rendering - Hydrating the client-side application
- Handling navigation on both server and client
Entry Files
Server Entry
Createapp/entry.server.tsx:
Client Entry
Createapp/entry.client.tsx:
SSR Configuration
Configure SSR inreact-router.config.ts:
Development Server
The dev server handles SSR automatically:- Intercepts incoming requests
- Loads the server build
- Executes route
loaderfunctions - Renders the React tree to HTML
- Returns the HTML response
Production Server
Using @react-router/serve
The simplest way to run your SSR app:Custom Server
Create a custom server with Express:Node.js Adapter
Convert Node.js requests to Web Fetch API:SPA Mode
Disable SSR for Single Page Application mode:- Only the root route and
HydrateFallbackare rendered at build time - An
index.htmlfile is generated - All navigation happens client-side
- No server is needed in production
Server vs. Client Code
Server-Only Modules
Code that should only run on the server:.server.ts suffix ensures this code is excluded from client bundles.
Client-Only Code
Use client-only imports:Streaming SSR
Use React streaming APIs for better performance:Middleware Mode
Integrate with existing servers:Environment Variables
Environment variables are handled automatically:Server Build Output
After building, the server output is inbuild/server/: