Published August 12, 2017
This repository is a sample code of the very, very simple Universal React Application, using React Router version 4 and Express.js.
The official tutorial is available at https://www.mokuji.me/article/universal-app-react-router.
Centralized Routes
With the support of React Router Config, all routes are managed in src/routes.js
, and the rendering code was optimized. This also enables us to render data components on the server.
Server-side Rendering with Fetch Data
Rather than the data are pre-defined as a variable inside Javascript file, the app fetches books
data which is saved as in JSON file and renders data component on both front and server side.
The application has the following pages.
This project was initialized with create-react-app. However, some modifications have been done in order to make it universal.
build: Build the production files based on the client-side app. In addition to the default react-scripts
task, this generates an index.ejs
based on the index.html
.
watch: Build non-hashed Javascript and CSS files, watching the file changes.
server: Run the production app.
server-dev: Run the development app, serving the index.ejs
from view
directory. Non-hashed files must be built with watch
before the initial run.
server-dev:watch: Run the development app with generating non-hashed files as watching file changes. Usually this script is to be used instead of watch
and server-dev
when you develop the server-side application.
Clone the repo and change the working directory:
$ git clone https://github.com/zacfukuda/universal-app-react-router
$ cd universal-app-react-router
Install the packages:
$ yarn
// Or if you use npm:
$ npm install
To develop as a client-side single-page app:
$ yarn start
The command will open the browser navigating to localhost:3000 and the browser will be refreshed every time you modify the files under src
directory.
Build & run the app:
$ yarn build
$ yarn server
Visit localhost:3000 and the source of the home page or the books page. You’ll see the all contents are rendered on the server.
Build & watch file changes:
$ yarn watch
Run the app in the development mode:
$ yarn server-dev
Run the two command above in parallel:
$ yarn server-dev:watch
Most of the cases, server-dev:watch
is sufficient.