The most basic server rendering in React Router is pretty straightforward. However, there's a lot more to consider than just getting the right routes to render. Here's an incomplete list of things you'll need to handle:
Setting all of this up well can be pretty involved but is worth the performance and UX characteristics you can only get when server rendering.
If you want to server render your React Router app, we highly recommend you use Remix. This is another project of ours that's built on top of React Router and handles all of the things mentioned above and more. Give it a shot!
If you want to tackle it on your own, you'll need to use <StaticRouterProvider>
or <StaticRouter>
on the server, depending on your choice of router. If using <StaticRouter>
, please jump down to the Without a Data Router section.
First, you'll need to define your routes for the data router, these routes will be used both on the server and in the client:
const React = require("react");
const { json, useLoaderData } = require("react-router-dom");
const routes = [
{
path: "/",
loader() {
return json({ message: "Welcome to React Router!" });
},
Component() {
let data = useLoaderData();
return <h1>{data.message}</h1>;
},
},
];
module.exports = routes;
esbuild
, vite
, or webpack
.
With our routes defined, we can create a handler in our express server and load data for the routes using createStaticHandler()
. Remember that the primary goal of a data router is decoupling the data fetching from rendering, so you'll see that when server-rendering with a data router we have distinct steps for fetching and rendering.
const express = require("express");
const {
createStaticHandler,
} = require("react-router-dom/server");
const createFetchRequest = require("./request");
const routes = require("./routes");
const app = express();
let handler = createStaticHandler(routes);
app.get("*", async (req, res) => {
let fetchRequest = createFetchRequest(req);
let context = await handler.query(fetchRequest);
// We'll tackle rendering next...
});
const listener = app.listen(3000, () => {
let { port } = listener.address();
console.log(`Listening on port ${port}`);
});
Note we have to first convert the incoming Express request into a Fetch request, which is what the static handler methods operate on. The createFetchRequest
method is specific to an Express request and in this example is extracted from the @remix-run/express
adapter:
module.exports = function createFetchRequest(req) {
let origin = `${req.protocol}://${req.get("host")}`;
// Note: This had to take originalUrl into account for presumably vite's proxying
let url = new URL(req.originalUrl || req.url, origin);
let controller = new AbortController();
req.on("close", () => controller.abort());
let headers = new Headers();
for (let [key, values] of Object.entries(req.headers)) {
if (values) {
if (Array.isArray(values)) {
for (let value of values) {
headers.append(key, value);
}
} else {
headers.set(key, values);
}
}
}
let init = {
method: req.method,
headers,
signal: controller.signal,
};
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = req.body;
}
return new Request(url.href, init);
};
Once we've loaded our data by executing all of the matched route loaders for the incoming request, we use createStaticRouter()
and <StaticRouterProvider>
to render the HTML and send a response back to the browser:
app.get("*", async (req, res) => {
let fetchRequest = createFetchRequest(req);
let context = await handler.query(fetchRequest);
let router = createStaticRouter(
handler.dataRoutes,
context
);
let html = ReactDOMServer.renderToString(
<StaticRouterProvider
router={router}
context={context}
/>
);
res.send("<!DOCTYPE html>" + html);
});
Once we've sent the HTML back to the browser, we'll need to "hydrate" the application on the client using createBrowserRouter()
and <RouterProvider>
:
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
import { routes } from "./routes";
let router = createBrowserRouter(routes);
ReactDOM.hydrateRoot(
document.getElementById("app"),
<RouterProvider router={router} />
);
And with that you've got a server-side-rendered and hydrated application! For a working example, you may also refer to the example in the Github repository.
As mentioned above, server-side rendering is tricky at scale and for production-grade applications, and we strongly recommend checking out Remix if that's your goal. But if you are going the manual route, here's a few additional concepts you may need to consider:
If any loaders redirect, handler.query
will return the Response
directly so you should check that and send a redirect response instead of attempting to render an HTML document:
app.get("*", async (req, res) => {
let fetchRequest = createFetchRequest(req);
let context = await handler.query(fetchRequest);
if (
context instanceof Response &&
[301, 302, 303, 307, 308].includes(context.status)
) {
return res.redirect(
context.status,
context.headers.get("Location")
);
}
// Render HTML...
});
If you're using route.lazy
in your routes, then on the client it's possible you have all the data you need to hydrate, but you don't yet have the route definitions! Ideally, your setup would determine the matched routes on the server and deliver their route bundles on the critical path such that you don't use lazy
on your initially matched routes. However, if this is not the case you'll need to load these routes and update them in place prior to hydrating to avoid the router falling back to a loading state:
// Determine if any of the initial routes are lazy
let lazyMatches = matchRoutes(
routes,
window.location
)?.filter((m) => m.route.lazy);
// Load the lazy matches and update the routes before creating your router
// so we can hydrate the SSR-rendered content synchronously
if (lazyMatches && lazyMatches?.length > 0) {
await Promise.all(
lazyMatches.map(async (m) => {
let routeModule = await m.route.lazy();
Object.assign(m.route, {
...routeModule,
lazy: undefined,
});
})
);
}
let router = createBrowserRouter(routes);
ReactDOM.hydrateRoot(
document.getElementById("app"),
<RouterProvider router={router} fallbackElement={null} />
);
See also:
First you'll need some sort of "app" or "root" component that gets rendered on the server and in the browser:
export default function App() {
return (
<html>
<head>
<title>Server Rendered App</title>
</head>
<body>
<Routes>
<Route path="/" element={<div>Home</div>} />
<Route path="/about" element={<div>About</div>} />
</Routes>
<script src="/build/client.entry.js" />
</body>
</html>
);
}
Here's a simple express server that renders the app on the server. Note the use of StaticRouter
.
import express from "express";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "./App";
let app = express();
app.get("*", (req, res) => {
let html = ReactDOMServer.renderToString(
<StaticRouter location={req.url}>
<App />
</StaticRouter>
);
res.send("<!DOCTYPE html>" + html);
});
app.listen(3000);
And finally, you'll need a similar file to "hydrate" the app with your JavaScript bundle that includes the very same App
component. Note the use of BrowserRouter
instead of StaticRouter
.
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
ReactDOM.hydrate(
<BrowserRouter>
<App />
</BrowserRouter>,
document.documentElement
);
The only real differences from the client entry are:
StaticRouter
instead of BrowserRouter
<StaticRouter url>
ReactDOMServer.renderToString
instead of ReactDOM.render
.Some parts you'll need to do yourself for this to work:
<script>
in the <App>
component.<title>
).Again, we recommend you give Remix a look. It's the best way to server render a React Router app--and perhaps the best way to build any React app 😉.