Hi guys, I’m working in a Meteor
+ React
project that requires using react-router
for server-side rendering (SSR). The current react-router
version is v3
and I followed a tutorial about SSR here. The steps in summary are:
- Create a common routes file
- Include the routes file in client-side router
// index.js
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
// import routes and pass them into <Router/>
import routes from './modules/routes'
render(
<Router routes={routes} history={browserHistory}/>,
document.getElementById('app')
)
- In the server-side: match the routes to the url, render the right component for each route
import { WebApp } from 'meteor/webapp';
import express from 'express';
const app = express();
app.get('*', (req, res) => {
// match the routes to the url
match({ routes: routes, location: req.url }, (err, redirect, props) => {
// `RouterContext` is what the `Router` renders. `Router` keeps these
// `props` in its state as it listens to `browserHistory`. But on the
// server our app is stateless, so we need to use `match` to
// get these props before rendering.
const appHtml = renderToString(<RouterContext {...props}/>)
// dump the HTML into a template, lots of ways to do this, but none are
// really influenced by React Router, so we're just using a little
// function, `renderPage`
res.send(renderPage(appHtml))
})
})
function renderPage(appHtml) {
return `
<!doctype html public="storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<link rel=stylesheet href=/index.css>
<div id=app>${appHtml}</div>
<script src="/bundle.js"></script>
`
}
WebApp.connectHandlers.use(app);
The problem here is that every time I navigate to a new route in client-side, it sends a new request to server to get the rendered page. In the tutorial app, there’s only a single initial request that is sent to server, from that time the client will take over and handle routing (which is the correct/expected behaviour).
Any thoughts/suggestions are welcome. Thanks !