react-ssr
🔍 Overview
react-ssr
is a simple and lightweight React server-side rendering solution that abstracts the complexities of server-side rendering React applications away from the codebase. react-ssr
adds another optional 'lifecycle' method to your components for fetching data.
⏳ Installation
$ npm install react-ssr --save
We recommend you use the babel plugin too. Add the babel plugin to your .babelrc
.
$ npm install babel-plugin-react-ssr --save-dev
You'll also need React 16.3 or higher and React Router 4. They're peerDependencies, obvs.
👋 Getting started
Hopefully you can get a simple page server-rendering in minutes. Efficiently. Here's everything you need to know.
Learn quicker by example? Check the sample app out.
1. Setting up the server
Assuming you have a simple express server setup, you'll just need to hand off your routes to react-ssr. Note that you can also pass a custom template that will be responsible for the 'HTML document' that wraps your React app. Copy the example from src/components/DefaultTemplate as a starting point.
const app = const renderer = appapp
2. Setting up the routes
You will need an array of static routes, which means each route will be an object (as per React Router v4's docs) and not a <Route />
. This is because a <Route />
can only be read once rendering begins. A static route can be matched against before rendering begins.
const routes = path: '/' exact: true component: HomePage path: '**' component: NotFoundPage
Check out data loading with server side rendering in React Router v4 to see other comments or examples.
Additionally, your React app entry point will need to hydrate those routes out, for example: -
const App = <BrowserRouter> </BrowserRouter> ReactDOM
3. Fetching data
There's one important rule: If you want to make a data call, and you'd like it to be server side rendered correctly, you'll need a static fetchData
method. react-ssr
will execute this before it begins rendering your app on the server and inject the result of it into the components props.
Heads up! We're using the static keyword below. You'll need to add the transform class properties babel plugin or another alternative to use this at the time of writing.
Here's an example:
Component static { if req && reqthing res // you can redirect the request return content: axios // becomes available as this.props.content } { if thispropsloading // react-ssr is calling fetchData client-side return <p>loading...</p> if thispropserror // react-ssr encountered an error calling your fetchData return <p>Fancy retry fetch UI...</p> console return <span /> } // alternative syntax...Navigation { return content: axios // becomes available as this.props.content } // only one data call? you can spread out the result into props...Navigation { return axios // becomes available as this.props[x], where x is every key returned in top of json tree response from this api call}
🏆 You should now have server-side rendering setup with asynchronous data calls.
⌨️ Options
There's two things to know in this section: arguments to fetchData
and options for react-ssr
.
Arguments to fetchData
static {}
Argument | Description |
---|---|
req | Node JS request object, server side only |
res | Node JS response object, server side only |
match | React route that was matched, contains params |
isServerRender | Shorthand boolean to know if executed from client or server |
Configuration for react-ssr
const renderer =
You can change your cache policy on-the-fly using middleware and also set the cache key suffix on-the-fly using middleware. This can be useful when you need flexibility on whether to cache or require a unique key based on feature flags being enabled on a given route, for example.
app.use((req, res, next) => {
if (userIsLoggedIn) {
res.locals.useSsrCacheForRequest = false
}
res.locals.ssrCacheKeyPrefix = 'tyrion' // redis key will now be `tyrion${req.url}`
res.locals.ssrCacheKeySuffix = 'drogon' // redis key will now be `tyrion${req.url}drogon` for given request
})
app.use(renderer)
Option | Description | Required | Default |
---|---|---|---|
routes | static routes array of your react app | yes | [] |
disable | disables server-side rendering | no | false |
ignore | array of route paths to skip SSR, just send document | no | false |
Html | override core html document template | no | see src/components/DefaultTemplate in repo |
Providers | wraps your routes, useful for context providers, etc | no | |
cache | allows caching of components or pages | no | { mode: 'none', duration: 1800 } |
📰 Notes
As data fetching occurs before rendering begins, you should consider:
- Components that are dynamically rendered with static
fetchData
will not be server-side rendered. So, if you're programatically doing something like the below, it will render withthis.props.loading
as true on the client, then fetch the data and rerender:
const DynamicComponent = components'MyComponent'return <DynamicComponent />
No babel plugin?
Two simple steps should be taken if you're giving that a skip, but we recommend you use it to abstract this nonsense away from your codebase. If you'd like an alternative, raise an issue or a PR :-)
Find out the steps you need to take without the babel plugin here.
💡 Contributing
This package is still early doors. Please do get involved, feel free to critique it, offer solutions that can change its approach slightly, or request examples on how you want to use it. Spotted a bug, need something adding? Raise an issue. Pull requests welcome. 👌