Routing prefix with server-side rendering?
See original GitHub issueMaybe I am missing something obvious here but I’ve got a React app that I’m rendering to string server side and then attaching again on the client, and the base URL for this particular app is: localhost:3000/prefix
. The mounting in express looks something like this:
app.use('/prefix', reactAppRouter); // server-side render happens in reactAppRouter.get('/', ...)
Now, because the .get()
above refers to '/'
, react router notes that I need '/'
in my routes. However, when I load the app client side, the client react app sees that the route is actually /prefix
and notes that I need that in my routes, too. So I end up with this:
var routes = (
<Route handler={App} path="/">
<Route handler={App} path="/prefix">
// all other routes go in here
</Route>
</Route>
);
And I’ve tried passing only one or the other, and in both cases it fails: removing the route to /
fails to render on the server, and removing the route to /prefix
fails to render on the client.
I’ve also tried this with a further nested route, and ended up with this nasty business:
var routes = (
<Route handler={App} path="/">
<Route handler={App} path="/prefix">
<Route handler={Test} path="/test"/>
<Route handler={Test} path="/prefix/test"/>
</Route>
</Route>
);
Again, everything works as expected, but I’m duplicating every single one of my routes in order to work like this.
Is there any way to avoid this? I can post the code for my express app if anyone needs to see it, but it’s pretty basic and follows the example react-router server side mounting I’ve found in the docs.
Checking for the existence of window
and adding a prefix dynamically seems to work to save on the code duplication, is this something we might be able to add in to react-router? For example:
Router.create({
routes: routes,
clientPrefix: 'prefix',
location: Router.HistoryLocation
}).run(........);
Thanks!
Issue Analytics
- State:
- Created 8 years ago
- Reactions:2
- Comments:6 (1 by maintainers)
By the way, the solution was to use req.originalUrl which matches the full path after the host and port number (i.e., localhost:3000/full/path), originalUrl will be
/full/path
which is exactly what React router expects, so this should issue should be closed but perhaps this could be noted somewhere for future reference.your top level route needs the prefix, that’s it.