Note: This article was written December 24 2013, when react-page's version number is 0.2.0. This is all likely to change, so if the advice mentioned doesn't help, please reach out to the React community.
Note: Technically, this functionality is provided by react-page-middleware
. I'm going to refer to it generally as react-page
, because I don't think they have enough of an independent identity (and usefulness outside of the whole react-page stack) to nitpick the naming.
react-page [https://github.com/facebook/react-page] is a cool new tool to link your ReactJS scripts in to your Node server config so that the entire site can be server rendered.
Unfortunately, it doesn't support custom routes - http://site.co/widget will always look for src/widget/index.js (or whatever your root elem is), even if you want http://site.co/widgets/new to go there instead.
In other words, there is no way to associate random URLs to specific controllers.
With Express, for instance, you would do something like:
app.get('/:id', require('./controllers/view_an_id/'));
I tried to hack one in, but there is no ability to pass in a 404 handler at all (which would have been my first junction point for wiring this in), nor is there a way that I could find to iterate through all the server-side objects and build a list of custom URLs from the definition of each.
To get around this problem, I took the old tried-and-true server-side URL rewriting approach.
I'm using nginx here, but the same concepts would work under Apache or any other platform.
I basically use this as my location block in my Nginx config file (lump.conf):
# pass the request to the node.js server with the correct headers and much more can be added, see nginx config options
location / {
rewrite ^/$ /index.html break;
rewrite ^/([A-Za-z0-9-]+)$ /view.html?q=$1 break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://app_lump/;
proxy_redirect off;
}
This basically transforms / to always trigger index.html, and triggers any random string (that matches our pattern) to hit view.html instead. My handler code for random URLs is then located in src/view/index.js
Enjoy!
@tlack