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 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.
6. 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"
6
10. ADVANTAGES...
🙉🙉 MOAR
Keep using React/JS paradigms also for "static" websites
Speed up content loading with linkprefetch
loige.link/universal-react-made-easy-talk
10
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);
// use ejs templates
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));
// render the index for every non-matched route
app.get('*', (req, res) => {
let markup = '';
let status = 200;
return res.status(status).render('index', { markup });
});
// start the server
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
server.listen(port);
"Static" Express server
53
55. RECAP
What we learned so far
1. Define views combining React components
2. Add routing using React Router
3. Compile the client bundle with Babel and Webpack
4. Run the app with a static Express server
55
57. Updating the server app
// ...
import { renderToString } from 'react-dom/server';
import { StaticRouter as Router } from 'react-router-dom';
import { App } from './components/App';
// ...
app.get('*', (req, res) => {
let markup = '';
let status = 200;
const context = {};
markup = renderToString(
<Router location={req.url} context={context}>
<App />
</Router>,
);
// context.url will contain the URL to
// redirect to if a <Redirect> was used
if (context.url) {
return res.redirect(302, context.url);
}
if (context.is404) {
status = 404;
}
return res.status(status).render('index', { markup });
});
57
59. 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 the Express app
59
60. UNIVERSAL DATA RETRIEVAL
api-proxy & async-props
(COMPLETE CHAPTER in )
UNIVERSAL STATE MANAGEMENT
Redux
PROGRESSIVE WEB APPS (PWA)
+
Node.js Design Patterns
@addyosmani's tutorial Create React App
WHERE DO WE GO
from here...
Code: loige.link/judo-heroes-2
60