Multiple React bundles on a single Express server (Part-1)

This is the sharing about setting up multiple React Apps to be hosted by a single Express server. Most of the web projects do not require this kind of setup.

In common practice, an Express server usually just hosts one React App. This should be the way to go most of the time.
------------------------------------------------------------------------
|                                                                      |
|   -------------                         ------------------           |
|   | React App |    <------------>       | Express server |           |
|   -------------                         ------------------           |
|                                                                      |
------------------------------------------------------------------------

In my current project, there is a need to have separate React Apps to be hosted by a single Express server. This is to allow control on user access while using a single Docker container.
------------------------------------------------------------------------
|                                                                      |
|    ---------------                                                   |
|    | React App 1 |    <------------>                                 |
|    ---------------                                                   |
|    ---------------                       ------------------          |
|    | React App 2 |    <------------>     | Express server |          |
|    ---------------                       ------------------          |
|    ---------------                                                   |
|    | React App 3 |    <------------>                                 |
|    ---------------                                                   |
|                                                                      |
------------------------------------------------------------------------

The question is, how to make it happens?
Below are the steps to make it happens.



Setup the hosting server


1. Create and get into the project folder.
mkdir multi-reacts
cd multi-reacts


2. Initialize the project and install dependencies for Express server.
npm init -y
npm i express body-parser

3. Create a 'server' folder, then create 'index.js', 'routes.js', 'server.js' files inside the folder
mkdir server
touch server/index.js server/route.js server/server.js

4. Add the code below to the 'index.js' file (server/index.js)
const server = require('./server')
const port = process.env.PORT || 3000
server.listen(port, function () {
 console.log('Listening on port', port)
})


5. Add the code below to the 'server.js' file (server/server.js)
const path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const server = express()
const apiRouter = require('./routes')

// body parsing
server.use(bodyParser.json()) // to support JSON-encoded bodies
server.use(bodyParser.urlencoded({ extended: true }))
server.use(express.static(path.join(__dirname, '../public')))
server.use('/api', apiRouter)

// Catch All: Show 404 at not supported pages
server.get('*', function (req, res) {
  res
    .status(404)
    .send(
      `<h1>Error 404</h1><p>Page is not available on</p><p>${
        req.originalUrl
      }</p>`
   )
})

module.exports = server


6. Add the code below to the 'routes.js' file (server/routes.js)
const express = require('express')
const router = express.Router()

router.get('/', (req, res) => {
  res.status(200).send('<h1>Hello World from the server</h1>')
})

module.exports = router



7. Create a 'public' folder, then create an 'index.html' file inside the folder
mkdir public
touch public/index.html


8. Add the code below to the 'index.html' file (public/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Welcome</title>
</head>
<body>
  <h1>Hello World from main page</h1>
</body>
</html>


9. In the 'package.json' file, update the line containing "main:" to look like below:
"main": "server/index.js",


10. In the 'package.json' file, update the line containing "script:" to look like below:
"scripts": {
    "start": "node server/index",
    "test": "echo \"Error: no test specified\" && exit 1"
  },


11. Checkpoint: Please do a trial run to see if everything above is done correctly.
First, type this command in the terminal:
npm run start

After entering the command, the terminal will say:
Listening on port 3000

Then, you could use any browser to open two links below:
http://localhost:3000/
http://localhost:3000/api

If you have done the setup correctly, you should be able to see the message of 'Hello World from the main page' and 'Hello World from the server'.

The source code up to this point should be like this:
 https://github.com/YWHo/multi-reacts/tree/setup_hosting_server



Next step, we are going to set up the first React APP.
Please go to the next post






Comments

Popular posts from this blog

Multiple React bundles on a single server Express server (Part-2)

100% Test Coverage?