Using Express for routing React Server side - javascript

Is it okay for a site to use Express for handling the routing when using Server side rendered React templates rather than React Router?
I am looking to use Fluxxor similar to this example for my components and stores/actions. Then I was planning to use Express router to handle the page routing server side, and on each route render the desired component to string. In this basic example below my app.js is a simple todo example using Flux but in production it would likely be a top level component appropriate for the routed page. e.g. /products would be a product component, with its subcomponents.
Here is my basic server.js file
var express = require('express');
var React = require('react');
var App = require('./app');
var app = express();
var port = 4580;
// include my browserify bundle.js
app.use('/public', express.static(__dirname + '/public'));
app.get('/', function(req, res) {
/* each route will render the particular component to string. */
var markup = React.renderToString(App());
res.send(markup);
});
// I will seperate my views out like this
// app.get('/products', product.list);
// app.get('/users', user.list);
// app.get('/products:id', product.list);
My basic server side render approach is here if that helps.
So as I was saying, Is it okay to use Express for the routing, as I am finding React Rouuter to be quite complex, and it just seems easier to have routes on the server, and to render each page with its components server-side.
Am I losing anything else here other than the complexity of handling the routing in Express rather than React Router? As I think I can handle that, but want to make sure I haven't messed up the point of server side rendering with React by just using Express to render to string based on different routes.
Just to be clear, I'm okay with the issues which React Router aims to solve, and understand that I will be doing something similar to what was suggested in the React Router overview as being problematic in the long run.
// Not React Router API
otherRouter.route('/', function () {
React.render(<DashboardRoute/>, document.body);
});
otherRouter.route('/inbox', function () {
React.render(<InboxRoute/>, document.body);
});
otherRouter.route('/calendar', function () {
React.render(<CalendarRoute/>, document.body);
});
While one level of shared UI like this is pretty easy to handle, getting deeper and deeper adds more complexity.
I am basically assuming that I can handle this complexity okay, whether that is true or not, I guess I will find out in time.

Sounds like you are trying to make your website isomorphic—rendering static markup on the server, attaching event listeners on the client.
The approach I use for my projects is embedding client-side javascript in the server-rendered string, so that the same props are passed down and re-rendering is not required on the client.
It seems to be very complicated to explain with only a few snippets of code, so check out this template I created for this purpose. There's also a tutorial about this topic here.

Related

Express mounting routes

I am looking at some code from someone else for learning purposes. The way they're mounting routes is vague to me.
app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist')))
// mount routes
app.use('/', userRoutes)
app.use('/', authRoutes)
app.use('/', postRoutes)
The confusing part for me is how they're using '/' and using app.use. I'm used to doing it with app.get() and on top of that you specify the route instead of putting '/' everywhere. How does this work? Is this better practice?
The repo I'm looking at is https://github.com/shamahoque/mern-social/tree/master/server
Writing routes directly can be confusing and difficult to manage if there are large number of routes. So according to MVC pattern, the application is divided into modules/logical blocks based on functionalities they perform. For example, a simple hospital management system can have authentication, billing, payroll , medical-stock , patients etc modules (imaginary). If you are building application using MVC pattern, the common practice is to write controller for each of the module. Express provides something called middleware also called as Router to attach these controllers to respective API routes (Imagine it as a sort of map that connects each route to respective controller).
Once you define routes for each of these modules through middleware, you use those routes with your application. These routes handle requests and send parameters to controller to process.
You can learn how to use Middleware and Routers here : https://www.tutorialspoint.com/expressjs/expressjs_routing.htm
Regarding quality of code, dividing the code into modules and using routers to connect them is less tedious for others to understand. It also provides a good view of the application and it becomes easier to add new modules / functionality.
You can read more about building production-ready express app here :
https://www.freecodecamp.org/news/how-to-write-a-production-ready-node-and-express-app-f214f0b17d8c/

React server rendering, getting the HTML to the browser

I'm attempting to setup a simple app where I use React server rendering.
React 0.14.8, Express 4.13.4.
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const express = require('express');
const exphbs = require('express-handlebars');
const myApp = React.createFactory(require('./app/components/app.jsx'));
// ...express/handlebars setup stuff here
app.get('/', function(req, res) {
const html = ReactDOMServer.renderToString(myApp());
res.render('home', { content: html });
});
My html variable contains the markup, however it's escaped and the browser shows the HTML.
I know about dangerouslySetInnerHTML(), however I really don't want to have to use that. It's named that for a reason.
So I'm left thinking that there must be something I'm missing here. As server rendering is quite a big feature of React, and dangerouslySetInnerHTML() is discouraged, the two don't really feel like they should be used together.
What am I missing..?
Can someone provide a really basic, bare-bones example of React server rendering..?
You're right, the only way to inject innerHtml when rendering, unfortunately, is by using that dreadfully named dangerouslySetInnerHTML() function. Basically it's asking you to really think about it before you do it. A nice example is written out here: https://camjackson.net/post/server-side-rendering-with-react
I think I was confused (it happens)... The HTML returned from renderToString() was actually ok, it was handlebars that was escaping the HTML.
In my Handlebars template file I changed {{content}} to {{{content}}} as per the docs: http://handlebarsjs.com/ (HTML Escaping).
The browser now renders the HTML as HTML instead of showing the HTML.
I feel I owe an apology to the ReactDOMServer.renderToString() method.
I'm sorry!

Conflicting node.js Express object/collection routes

I have the following Node Express routes...
get('/api/dogs')
get('/api/dogs/:id')
get('/api/dogs/breeds')
You can probably see the problem already. The routing gets confused when calling the 'breeds' route thinking I am trying to call the 'dogs/:id' route.
Is there a way to get around this? Or should I just create a unique route, something like 'api/dog-breeds'? I'd like to keep them all under the same resource because I am using the Express' modular 'router' object.

Combining react and jade

I am working on an isomorphic javascript app with express + react. We started out using jade for server side templates for static content, but combining the two is quickly becoming unwieldy. We have ended up with something like this:
In the express routes:
router.get("/", function(req, res) {
var webpackStats = require('../../config/webpack-stats.json');
var reactHtml = React.renderToString(HiwApp({}));
var slideshowHtml = React.renderToString(slideshowApp({}));
var config = {
webpackStats: webpackStats,
reactOutput: reactHtml,
slideshowHtml: slideshowHtml
};
res.render("how_it_works/howitworks", config);
});
In Jade:
body
.company-logo.center
#react-main-mount
!= reactOutput
include ./content_block_1.jade
include ./content_block_2.jade
#slideshow-main-mount
!= slideshowHtml
This is very brittle-if we want jsx then a jade template then more jsx, we have to make sure we get the order right.
My idea is to do it all with jsx. I know there is React.renderToStaticMarkup for this sort of thing, but that doesn't solve the problem of mixing dynamic with static pages.
The big questions: if we decide to do all of this with jsx (say layout.jsx which contains all components), then call React.renderToString(App({});, will this be a major performance hit? If so, is there a better way to do it to easily combine static and dynamic blocks?
Although this may be a tiny bit off topic: We stuck with jade templates.
Basically we wanted the flexibility to use a non-react + flux architecture for areas of the site when and if that need arose. Our site is basically made up of a number of smaller SP apps: Site, UserAccount, Team and Admin.
Why did we do this?
Smaller filesize and overhead for users who are not accessing all sections of the site.
Option to "opt out" of React and flux if and when the need arises.
Simpler, server side authentication.
The way we have done it successfully was to render a JSX shell template (Html.jsx) on the server using React.renderToStaticMarkup() and then send it as the response to every server-side express route request that is meant to deliver some HTML to the browser. Html.jsx is just a shell containing html head information and GA scripts etc. It should contain no layout.
// Html.jsx
render(){
return (
<html>
<head>
// etc.
</head>
<body>
<div
id="app"
dangerouslySetInnerHTML={{__html: this.props.markup}}>
</div>
</body>
<script dangerouslySetInnerHTML={{__html: this.props.state}</script>
<script>
// GA Scripts etc.
</script>
</html>
)
}
Remember it is totally fine and even recommended to use dangerouslySetInnerHTML on the server when hydrating your app.
Dynamic layout should be done with your your isomorphic components through a hierarchy of components based on their state/props configuration. If you happen to be using React Router, then your router will render view handlers based on the routes you provide it so that means you don't need to manage that yourself.
The reason we use this technique is to architecturally separate our "App" which is isomorphic and responds to state from our server-side template shell which is just a delivery mechanism and is effectively boiler plate. We even keep the Html.jsx template amongst all the express components within our app and do not let it mix with the other isomorphic React components.
One of the most helpful resources I found for working out React/isomorphic architecture was https://github.com/yahoo/flux-examples/tree/master/react-router which is where we stole this technique from.
We explored the idea of integrating handlebars as a templating engine for client's devs using our products in the future but decided that it was less complex to write our own DSL in JSX and use some simple parsing routines to parse our HTML-like DSL to JSX by adding things like export default (ES6 module syntax) at the start of the template and then import the template to a rendering component.
You could of course follow that line of thought and use a jade compiler to spit out the template and then add module syntax around that if you think separate jade files are essential. I also noticed this project as well although I have not explored it in anger: https://github.com/jadejs/react-jade.

Express.js routeing for multiple projects running on one server

I'm quite new to node.js, and pretty new to Javascript (I don't count simple animations with jQuery as js). As a web-developer, I'm moving from PHP/MySQL to Express/mongo.
I like the idea of things being neat - as long as there isn't a noticeable loss in performance. As node is so rapidly developing, I'm finding it hard to find specific opinions and answers to my routeing methods for the current version of node (Most posts I find seem to be irrelevant and older than 2 years).
|- app.js
|- routes
|- blog.js
I'm using blog.js as the gateway for all blog-related stuff. This includes registering GET and POST requests with a function, and handling page-rendering.
This is all fired up with one call.
My app.js has the following:
... //basic express installation
var db = ... //mongoose database connection
require('./routes/blog')(app, db, '/blog'); //starts the blog up
blog.js looks like this:
var db = null;
var basedir = null;
module.exports = function(app, _db, _basedir){
db = _db;
basedir = _basedir;
app.get (basedir, pages.home );
app.get (basedir + '/show/:id', pages.getBlog );
/*app.get(basedir + '/*', function(req, res) {
res.redirect(basedir);
});*/
};
var pages = {
home : function(req, res) {
// whatever
}
, getBlog : function(req, res) {
// whatever
}
}
I know this works - my question, is if this is conventional? Is it something that isn't recommended? Is it memory-wasteful? Why do people place app.gets in app.js rather than an external file? What are the current mainly used routeing methods (I develop multiple small applications all on the same server, hence my wish for my app.js to be as minimal as possible).
The way you've outlined is perfectly acceptable, and in my mind, preferred to just having one big app.js file with all your routes and everything else in it.
Many people take the separating of code much further than what you've outlined, especially when trying to follow MVC and MVC-like patterns.
For example, here's a boilerplate project I'd been working on that might even go a little overboard on separation. It's not a finished product, just something I was playing with that took some of the different bits I liked from other boilerplates, frameworks, etc. I've learned some things since then and I might adjust it at some point.
NemoJS - My node/express/mongoose/jade/stylus/twitter_bstrap boilerplate project
One thing to keep in mind is the more you separate it, the more difficult it CAN be to track down problems. Not a good enough reason for not staying organized though. Which is essentially what our goal is, right?

Categories