Server Side React + EJS
Yesterday, I mentioned that my app’s webpages (at constellational.com) were being generated by joining strings. This is a way around that, using EJS to place the server side react data into an html template. The template itself is simple:
<html> Â <head> Â Â <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> Â Â <meta name='viewport' content='width=device-width, initial-scale=1' /> Â Â <link rel='stylesheet' type='text/css' href='/style.css' Â Â <title>Constellational</title> Â </head> Â <body> Â Â <div id='react-mount'><%- react -%></div> Â Â <script src='/main.js' type='text/javascript'></script> Â </body> </html>
All I’ve done is add <%- react -%> where I want my react string to be inserted. I’ve placed this file in a folder called templates, and made a small change to the code that serves the user pages:
var render = require('koa-ejs');
render(app, {root: 'templates'});
app.use(function *() { Â var splitURL = this.url.split('/'); Â splitURL.shift(); Â var username = splitURL.shift().toLowerCase(); Â var id = splitURL.shift(); Â var user = yield fetchUser(username).then((user) => { Â Â if ((id) && (user.posts.indexOf(id) > 0)) { Â Â Â user.posts.splice(user.posts.indexOf(id), 1); Â Â Â user.posts.unshift(id); Â Â } Â Â var promiseArr = user.posts.map(id => fetchPost(username, id)); Â Â return Promise.all(promiseArr).then((data) => { Â Â Â user.posts = data; Â Â Â return user; Â Â }); Â }); Â var reactString = ReactDOMServer.renderToString(React.createElement(views.User, user)); Â yield this.render('layout', {react: reactString}); });
Add koa-ejs to your list of dependencies (in your package.json) and Heroku will take care of the rest! This fixes #11.













