Setup react and express on same server

Last updated : Feb 13, 2022

This article will explain you how to integrate react and express application on same server.

When you are working on a MERN stack project you will manually need to integrate your frontend and back end parts of the application. Unlike any PHP or JAVA framework where it's setup automatically, its not the case with Express framework applications.

The way we will choose to do it
The main hosting is where our frontend application lives. Usually that is public_html directory in case of managed server and /var/www/html directory in case of Linux unmanaged server.

What we will do here is whatever route is written in browser's url bar will be handled by frontend application. And for backend we will create a prefix for eg. /api, so whichever route containing /api and rest of the url after that, the route will be reverse proxied to backend server which is hosted on some other port.

We will use a feature of web servers called Reverse proxy.

What is reverse proxy
According to Wikipedia, "In computer networks, a reverse proxy is the application that sits in front of back-end applications and forwards client (e.g. browser) requests to those applications. Reverse proxies help increase scalability, performance, resilience and security. The resources returned to the client appear as if they originated from the reverse proxy itself."

You can further read about reverse proxy in detail at https://en.wikipedia.org/wiki/Reverse_proxy.

So let's see how to setup react and express on same server using a method called reverse proxy

We are not creating a full fledged app in this article. We will just create a very basic frontend application in React js with two buttons for get and post requests to our Node js backend server so you can understand how to setup both applications on same server and further modify apps for additional features.

Let's get started.

First in Apache web server in Windows OS

First of all we will need to install/uncomment a library for enabling reverse proxy in Apache web server. For this open Xampp installation directory and go to apache/conf and open httpd.conf file.

After that search mod_proxy.so and you will get a line #LoadModule proxy_module modules/mod_proxy.so. All you have to do is remove that # from the line and uncomment it.

Next we will setup the configuration for proxying the backend url in Apache's httpd.conf. So go to Xampp's install directory and then in apache/conf/extra directory and open httpd-vhosts.conf file.

After opening the file, search ServerName localhost and you will get a block of code between <VirtualHost *:80> tags. Before the closing tag add one more block for /api location by typing following script.

<Location /api>
	ProxyPass http://127.0.0.1:3000
	ProxyPassReverse http://127.0.0.1:3000
</Location>

So now any request which has api included will be forwarded to the server we are specifying. For eg. if there is a request http://localhost/api/login, so it will be forwarded to http://127.0.0.1:3000 which is our Node js server.

We have setup the configuration of server with reverse proxy. Now let's setup the app.
Frontend in React

Open up a terminal and enter

npx create-react-app app-one

This command will create React project with the directory named app-one.

Now type in

code .

This command will open new created directory in Visual studio code. You can use any code editor.

We will not create any new component for this app. We will use existing component. So open App.js and enter following script.

import React from 'react';
import './App.css';

export default class App extends React.Component {
	constructor(props){
		super(props);
		
		this.state = {
		  local_email: '',
		  local_pass: '',
		  response_msg: 'Response will be displayed here'
		};

		this.hello_from_backend = this.hello_from_backend.bind(this);
		this.login_from_backend = this.login_from_backend.bind(this);
		this.update_email = this.update_email.bind(this);
		this.update_password = this.update_password.bind(this);
	}

	update_email(evt){
		var email = evt.target.value;
		this.setState({local_email: email});
	}

  
	update_password(evt){
		var pass = evt.target.value;
		this.setState({local_pass: pass});
	}

	hello_from_backend(evt){
		fetch('http://localhost/api/hello',{
		  method: 'GET'
		})
		.then(res => res.json())
		.then(r => {
		  this.setState({response_msg: 'Welcome '+this.state.local_email+ '. '+r});
		})
		.catch(err => {
		  this.setState({response_msg: JSON.stringify(err)});
		});
	}

	login_from_backend(evt){
		fetch('http://localhost/api/login',{
		  method: 'POST',
		  headers:{
			'Content-Type':'application/json'
		  },
		  body: JSON.stringify({email: this.state.local_email,pass: this.state.local_pass})
		})
		.then(res => res.json())
		.then(r => {
		  this.setState({response_msg: 'Login successful with email: '+r.email});
		})
		.catch(err => {
		  this.setState({response_msg: JSON.stringify(err)});
		});
	}

	render(){
		return(
		  <div>
			<div className="msg-panel">
			  {this.state.response_msg}
			</div>

			<br/>

			<input type="text" placeholder="enter email" onChange={this.update_email} />
			<br/>

			<input type="password" placeholder="enter password" onChange={this.update_password} />
			<br/>
			
			<input type="button" className='btn' value="Hello from backend" onClick={this.hello_from_backend}/>
			
			<input type="button" className='btn' value="Login from backend" onClick={this.login_from_backend}/>

		  </div>
		);
	}
}

Now we need some styling for our application's UI. So open App.css and enter the following code.

.msg-panel {
  margin:0;
  padding:5px;
  background-color: rgb(1, 59, 168);
  color:white;
  text-align: left;
  font-size: 22px;
}

input[type=text], [type=password]{
  border:1px solid black;
  padding:5px;
  margin:10px;
  font-size: 15px;
}

.btn{
  display:flexbox;
  margin:10px;
  padding:5px 8px;
  background-color: rgb(2,135,209);
  color:white;
  box-shadow: 0 0 3px #000000;
}
.btn:hover{
  transition: 0.4s;
  background-color: rgb(202,202,202);
  color:rgb(2,135,209);
}

We have completed the frontend of the application.
Now Back end in Node js

Create a directory named app-backend and open up command prompt enter the directory you just created and type in the following.

npm i express cors --save

This command will install express framework and cors package. You will need cors package only while development in order to connect your application's frontend with backend.

Now open this directory in Visual studio code and create a file named server.js and enter the following script.

var express = require('express');
var cors = require('cors')
var app = express();
var bodyParser = require('body-parser')

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 
//app.use(cors())

app.get('/hello',function(req,res){
    res.setHeader("Content-Type","application/json");
    res.write(JSON.stringify("Hello from app backend"));
    res.end();
});

app.post('/login',function(req,res){
    res.setHeader("Content-Type","application/json");
	var ret_arr = {
		email: req.body.email,
		pass: req.body.pass
	};
    res.write(JSON.stringify(ret_arr));
    res.end();
});

app.listen(3000,function(err){
    if(err){
        console.error(err);
    }
    else{        
        console.log("server running at port 3000");
    }
});

Now you can test your application by building the production version of frontend application. For getting production build open app-one in Visual studio code once again and open package.json and add a line "homepage": "/build/", after the name property. This line is added to provide a directory for loading all static files to frontend application when applcation is uploaded to live server.

After this open command prompt and enter the directory app-one and simply type in the following.

npm run build

Now you can test your application by browsing http://localhost/build/.

You can also watch video here to learn more about setting up Node js & React app in same server.

That is it for setting up react and express on same server. After understanding this process, you can modify this application completely and can create whatever the requirement is.
And also through this article you can setup react and express application on same live unmanaged server.



Sign in for comment. Sign in