Since we started to see JS on the server side, the dream of developers has been to reduce the gap and the cost of switch between frontend/backend. Today with Node.js, React and a whole ecosystem of tools, this dream is becoming true! In this talk I am going to discuss about Universal (a.k.a. Isomorphic) JS and present some practical example regarding the major patterns related to routing, data retrieval and rendering. I will use Node, React, Webpack, Babel and React Router and give you a series of example to get you started easily with this new technology trend.
3. AGENDA
1. The term "Universal" JS
2. Who & Why
3. Common problems and technologies
4. Building a frontend only Single Page App
5. Making it universal
3
53. // src/server.js
import path from 'path';
import { Server } from 'http';
import Express from 'express';
const app = new Express();
const server = new Server(app);
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));
// start the server
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
server.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
Static Express server
53
55. RECAP
What we learned so far
1. Define views combining React components
2. Add Routing using React Router
3. Compiling our frontend bundle with Babel
and Webpack
4. Run the app with a static Express server
55
60. // ...
// universal routing and rendering
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message);
}
// in case of redirect propagate the redirect to the browser
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname +
redirectLocation.search);
}
// generate the React markup for the current route
let markup;
if (renderProps) {
// if the current route matched we have renderProps
markup = renderToString(<RouterContext {...renderProps}/>);
} else {
// otherwise we can render a 404 page
markup = renderToString(<NotFoundPage/>);
res.status(404);
}
// render the index template with the embedded React markup
return res.render('index', { markup });
}
);
}); 60
62. RECAP
What we learned so far
1. Create a Single Page Application with
React and React Router
2. Add server side routing and rendering
using React and React Router libraries in out
Express app
62
63. UNIVERSAL DATA RETRIEVAL
api-proxy & async-props
(COMPLETE CHAPTER in )
UNIVERSAL STATE MANAGEMENT
Redux
Node.js Design Patterns
WHERE DO WE GO
from here...
Code: https://github.com/lmammino/judo-heroes-2
63