Minimal React Express SSR Working Example in 10 lines of Code
What we expecting is calling some URL and got back the HTML.
The traditional way the web work before web app.
Usual way: Template engine
The normal way achieving this is using the “template engine” or “rendering engine”. It is the engine that fill html
with the data.
The simplest form of the engine work like below:
const template = `<h1>{{ word }}</h1>`
const data = 'Hello'// Engine
template.replace(/{{ word }}/, word)
The normal engine is: pug
, ejs
,handlebars
etc.
The differences among them is the syntax and styles.
Use React as Rendering engine
But sometimes when you have a team already familiar with React, why not just using React for this simple tasks.
The demo is here below
const express = require('express')
const app = express()
const ReactDOMServer = require('react-dom/server')
const React = require('react')const element = React.createElement('div', null, 'Hello')
const rendered = ReactDOMServer.renderToStaticMarkup(element)
app.get('/', (req, res) => {
res.send(rendered)
})app.listen(3333, () => {
console.log('Working on 3333);
});
What is missing?
- Normal syntax of React component → need barbel
- Normal flow of Express
render
and injected data i.e.render(page, data)
Production setup
We add the engine here express-react-views
actually it implements something like above code plus the missing part.
const express = require('express')
const app = express()
app.set('views', __dirname + '/views')
app.set('view engine', 'jsx')
app.engine('jsx', require('express-react-views').createEngine())app.get('/', (req, res) => {
return res.render('index', {word: 'hello world'})
})app.listen(3333, () => {
console.log('Working on 3333);
});
Then creating the views
folder containing index.jsx
this name must match the name in res.render(‘index’)
and below is the React component
import React from "react";
export default function App({word}) {
return (
<div>
<h1>{word}</h1>
</div>
);
}
Here we are. Got Hello world.
Cheers !