0% found this document useful (0 votes)
24 views

Integrate React With Node - Js Express On Same Server:Port - BezKoder

This document discusses integrating a React client application with a Node.js/Express backend API so that they can run on the same server and port. It provides steps to build the React app, set up an Express server, and serve the React build from Express. Key points covered include building the React app, configuring routing to avoid 404 errors on refresh, and running both the frontend and backend on a single port.

Uploaded by

axel.pranav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Integrate React With Node - Js Express On Same Server:Port - BezKoder

This document discusses integrating a React client application with a Node.js/Express backend API so that they can run on the same server and port. It provides steps to build the React app, set up an Express server, and serve the React build from Express. Key points covered include building the React app, configuring routing to avoid 404 errors on refresh, and running both the frontend and backend on a single port.

Uploaded by

axel.pranav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Integrate React with Node.

js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Search… 

Download Free
O'Reilly eBook
Successfully experiment
and integrate product
features in your so!ware
Integrate React with Node.js Express on same applications
Server/Port
Split So!ware
! Last modi!ed: December 4, 2020 (https://bezkoder.com/integrate-react-express-same-server-port/) "
bezkoder (https://bezkoder.com/author/bezkoder/) # Full Stack (https://bezkoder.com/category/full-
stack/), Node.js (https://bezkoder.com/category/node-js/), React (https://bezkoder.com/category/react/)

Open
In this tutorial, I will show you step by step to integrate React project with Node.js Express
Rest API so that we only need to run both on same Server/Port. You will also know how to
configure React SPA Routing to avoid 404 on refresh.

Related Posts:
– React + Node.js Express + MySQL: CRUD example (https://bezkoder.com/react-node-
express-mysql/)
– React + Node.js Express + PostgreSQL: CRUD example (https://bezkoder.com/react-
node-express-postgresql/)
– React + Node.js Express + MongoDB: CRUD example (https://bezkoder.com/react-node-
express-mongodb-mern-stack/)
– React + Node.js Express + MySQL/PostgreSQL: JWT Authentication example
(https://bezkoder.com/react-express-authentication-jwt/)
– React + Node.js Express + MongoDB: JWT Authentication example
(https://bezkoder.com/react-node-mongodb-auth/)

Serverless:
– React Firebase CRUD with Realtime Database (https://bezkoder.com/react-firebase-
crud/)
– React Firestore CRUD App example | Firebase Cloud Firestore
(https://bezkoder.com/react-firestore-crud/)

Contents [hide]

React & Node.js Express Application Overview


Technology Stack
Setup React Client
Setup Express Server More ▼
Ad forceofnatureclean.com
Integrate React with Node.js Express
Build React App

https://bezkoder.com/integrate-react-express-same-server-port/ Page 1 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Integrate React production into Node.js Project


Serve React App from Express
Run Express and React on same Port
React Router 404 Not found on Refresh
Conclusion
Further Reading
Source Code

React & Node.js Express Application Overview


Launch Your
Assume that we have 2 separated projects: React & Node.js Express like this-
Website
You'll need: A studio. A
second job. And an
online store. Launch it
with Squarespace.

Squarespace

Open

For example, if we run them separately:

Express Server exports Rest Apis at Url: http://localhost:8080/


React Client runs at url: http://localhost:8081/

Using React to call Express Rest API:

HA Proxy GUI
HA Proxy GUI and HA Proxy
Reporting

https://bezkoder.com/integrate-react-express-same-server-port/ Page 2 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Otherwise, when deploying React production-build with Node.js Express project, we only
need to run Node Project for the fullstack (React + Node) system.

In this example, we access http://localhost:8080/ .

Technology Stack
Node.js
Express
React 16
React Router
React Scripts 3

Setup React Client

https://bezkoder.com/integrate-react-express-same-server-port/ Page 3 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

You can use your own React Project, or just download the source code on Github
(https://github.com/bezkoder/react-crud-web-api), or follow these steps to create a new
one.

Open cmd and create a new React Project as following command:

npx create-react-app react-crud

After the process is done. We create additional folders and files like the following tree:

$ public

$ src

$ components

! add-tutorial.component.js

! tutorial.component.js

! tutorials-list.component.js

$ services

! tutorial.service.js

! App.css

! App.js

! index.js

! package.json

Because I want to keep this tutorial simple and brief, please continue to develop this App
with instruction in the post:
React.js CRUD example to consume Web API (https://bezkoder.com/react-crud-web-api/)

Setup Express Server


You can use your own Node.js Project, or just download the source code on Github (), or
follow these steps to create a new one.

First, we create a folder:

$ mkdir react-express-mysql
$ cd react-express-mysql

Next, we initialize the Node.js App with a package.json file:

https://bezkoder.com/integrate-react-express-same-server-port/ Page 4 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

npm init

name: (react-express)
version: (1.0.0)
description: integrate React and Node.js Express Rest Apis on same server
entry point: (index.js) server.js
test command:
git repository:
keywords: react, nodejs, express, sequelize, rest, api
author: bezkoder
license: (ISC)

Is this ok? (yes) yes

The instruction can be found in one of the posts:


– Node.js Rest APIs example with Express, Sequelize & MySQL
(https://bezkoder.com/node-js-express-sequelize-mysql/)
– Node.js Rest APIs example with Express, Sequelize & PostgreSQL
(https://bezkoder.com/node-express-sequelize-postgresql/)
– Node.js Rest APIs example with Express, Sequelize & MongoDb
(https://bezkoder.com/node-express-mongodb-crud-rest-api/)

Let’s continue to the most important part.

Integrate React with Node.js Express


Build React App
Currently React Client and Express server work independently on ports 8081 and 8080 .

The first thing we need to do is to build React App for production.

Run command:
– npm run build
– or yarn build

PS D:\Projects\ReactProjects\react-crud> npm run build

> [email protected] build D:\Projects\ReactProjects\react-crud


> react-scripts build

Creating an optimized production build...


Browserslist: caniuse-lite is outdated. Please run the following command: `yarn upgrade`
Compiled successfully.

File sizes after gzip:

52.63 KB build\static\js\2.8091b331.chunk.js
22.44 KB build\static\css\2.47e06e2e.chunk.css
2.38 KB build\static\js\main.2cd554a3.chunk.js
774 B build\static\js\runtime-main.efee8004.js
144 B build\static\css\main.9c6cdb86.chunk.css

The project was built assuming it is hosted at /.


You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.


You may serve it with a static server:

yarn global add serve


serve -s build

Find out more about deployment here:

bit.ly/CRA-deploy

https://bezkoder.com/integrate-react-express-same-server-port/ Page 5 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Now you can see new build folder with content as following:

Integrate React production into Node.js Project


In app folder of Node.js Express Project, let’s create views folder.

$ app

$ config

$ controllers

$ models

$ routes

$ views

! index.js

! package.json

! server.js

Now we need to copy all files from React build folder to app/views folder above.

The final Node.js Project folder structure will be like this:

https://bezkoder.com/integrate-react-express-same-server-port/ Page 6 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Serve React App from Express


We’re gonna serve static files such as HTML files, CSS files and JavaScript files in
app/views folder using the express.static() built-in middleware function.

const express = require("express");

const path = __dirname + '/app/views/';


const app = express();

app.use(express.static(path));

Now, we can load the files in the static directory:

http://localhost:8080/index.html
http://localhost:8080/static/css/2.47e06e2e.chunk.css
http://localhost:8080/static/js/2.8091b331.chunk.js

The final step is to deliver index.html file using res.sendFile() . We will need to pass in
a path to the file.

// const path = __dirname + '/app/views/';

app.get('/', function (req,res) {


res.sendFile(path + "index.html");
});

https://bezkoder.com/integrate-react-express-same-server-port/ Page 7 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Now content in server.js file is like this-

const express = require("express");


const bodyParser = require("body-parser");
const cors = require("cors");

const path = __dirname + '/app/views/';

const app = express();

app.use(express.static(path));

var corsOptions = {
origin: "http://localhost:8081"
};

app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const db = require("./app/models");

db.sequelize.sync();

app.get('/', function (req,res) {


res.sendFile(path + "index.html");
});

require("./app/routes/turorial.routes")(app);

// set port, listen for requests


const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});

Run Express and React on same Port


Run the Node.js Express server (including React client) with commands:
node server.js

Open browser with url: http://localhost:8080/ .


Now you can see the result:

https://bezkoder.com/integrate-react-express-same-server-port/ Page 8 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

React Router 404 Not found on Refresh


Oh yeah! Everything looks good.
But wait, let’s try to refresh the page.
What happened?

To handle this error, we’re gonna enable hash(#) in React App Routing by using
HashRouter (https://reactrouter.com/web/api/HashRouter) .
It will keep the UI route in hash part of the URL, which should not make the server return
404.

So, in React Project, let’s open index.js file and change BrowserRouter into
HashRouter .

import React from "react";


import ReactDOM from "react-dom";
import { HashRouter } from "react-router-dom";

import App from "./App";


import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
<HashRouter>
<App />
</HashRouter>,
document.getElementById("root")
);

serviceWorker.unregister();

https://bezkoder.com/integrate-react-express-same-server-port/ Page 9 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Don’t forget to rebuild the React App and copy all files and folders in build directory (React
project) into views (Node.js Express project).

Now Our Url is hashed(#) after port number: http://localhost:8080/#/tutorials

Now you can refresh the page without worrying about 404.

Conclusion
Today we’ve learned how to integrate React with Node.js Express on same Server/Port. We
also handle the case React Router 404 Not found on Refresh by adding hash(#) to the urls.

There are many React + Express examples that you can apply this approach to integrate:
– React + Node.js Express + MySQL: CRUD example (https://bezkoder.com/react-node-
express-mysql/)
– React + Node.js Express + PostgreSQL: CRUD example (https://bezkoder.com/react-
node-express-postgresql/)
– React + Node.js Express + MongoDB: CRUD example (https://bezkoder.com/react-node-
express-mongodb-mern-stack/)
– React + Node.js Express + MySQL/PostgreSQL: JWT Authentication example
(https://bezkoder.com/react-express-authentication-jwt/)
– React + Node.js Express + MongoDB: JWT Authentication example
(https://bezkoder.com/react-node-mongodb-auth/)

Further Reading
https://www.npmjs.com/package/express
(https://www.npmjs.com/package/express)
React Component (https://reactjs.org/docs/react-component.html)
https://reactrouter.com/web/api/ (https://reactrouter.com/web/api/)

Source Code
You can find the complete source code for this tutorial at Github
(https://github.com/bezkoder/react-express-mysql).

https://bezkoder.com/integrate-react-express-same-server-port/ Page 10 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

Free Experimentation eBook


Ad Successfully experiment and
Ad integrate product features in your…
Split Software

Open

Share & Get Paid Node.js, Express Build Your App React.js +
& MongoDb: without Coding Node.js +
Build a CRUD… Express +…
Ad SurveyJunkie.com bezkoder.com Ad Appy Pie bezkoder.com

Cybercrime Login Page with React + Node.js React.js CRUD


Investigation React.js, + Express + example to
MongoDB:… PostgreSQL… consume Web…
Ad Boston University MET bezkoder.com bezkoder.com bezkoder.com

integration (https://bezkoder.com/tag/integration/) node.js (https://bezkoder.com/tag/node-js/)

react (https://bezkoder.com/tag/react/) rest api (https://bezkoder.com/tag/rest-api/)

Leave a Reply

Your email address will not be published. Required !elds are marked *

Comment

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

POST COMMENT

% Vue.js + Node.js + Express + MongoDB example: MEVN stack CRUD Application (https://bezkoder.com/vue-node-express-

https://bezkoder.com/integrate-react-express-same-server-port/ Page 11 of 12
Integrate React with Node.js Express on same Server/Port - BezKoder 3/5/21, 2:55 PM

mongodb-mevn-crud/)

Upload & resize multiple images in Node.js using Express, Multer, Sharp & (https://bezkoder.com/node-js-upload-resize-multiple-
images/)

FOLLOW US TOOLS

(https://www.dmca.com/Protection/Status.aspx?
" Json Formatter (https://bezkoder.com/json-formatter/) ID=3f543dd5-c6d8-4208-9a6b-
0e92057fd597&refurl=https://bezkoder.com/integrate-
(htt react-express-same-server-port/)

ps://

ww

w.yo

utub

e.co

m/c

han

! nel/ #

(htt UCp (htt

ps:// 0mx ps://

face 9RH gith

boo 0Jxa ub.c

k.co Fsm om/

m/b MvK bezk

ezko XA8 oder

der) 6Q) )

Home (https://bezkoder.com/) Privacy Policy (https://bezkoder.com/privacy-policy/) BezKoder 2019

Contact Us (https://bezkoder.com/contact-us/) About Us (https://bezkoder.com/about/)

https://bezkoder.com/integrate-react-express-same-server-port/ Page 12 of 12

You might also like