Setting up Nodejs Backend for a React App

Published on Oct 18, 2018

6 min read

NODEJS

In this article, I am going to walk you through setting up your own Node.js backend server for a React application. Both frameworks are often used together to build real time, fullstack web applications. A database, such as MySQL, Postgresql, or a NoSQL database such as MongoDB, is used to store information. For brevity’s sake, I will not use a database in this walkthrough.

Requirements: You need Node.js and npm installed on your local machine as well as create-react-app installed as a global dependency. If you do not have it, run the following command and install it.

npm install -g create-react-app

In some cases, you might have to give root permissions when installing a global dependency.

For the Nodejs backend, I am going to use HapiJS. If you are not familiar with it, it will be fun as you will be learning a lot of new things.

Getting Started with the Backend

🔗

To start, we need an empty directory inside which we can have our server and client live alongside each other. Initialize it by running the command npm init and you are ready to install Hapijs as a framework to build the web server.

npm install hapi --save

After Express, Hapi is quite popular among teams and individuals who write the server side of their application using Node. Hapi is currently being used by organizations such as Walmart and Yahoo and has an active community. After the dependency is successfully installed, create a new file called server.js.

1'use strict';
2
3const Hapi = require('hapi');
4
5// Create a server with a host and port
6const server = Hapi.server({
7 host: 'localhost',
8 port: 8000
9});
10
11// Add the route
12server.route({
13 method: 'GET',
14 path: '/',
15 handler: (request, h) => {
16 return 'hello world';
17 }
18});
19
20// Start the server
21async function start() {
22 try {
23 await server.start();
24 } catch (err) {
25 console.log(err);
26 process.exit(1);
27 }
28
29 console.log('Server running at:', server.info.uri);
30}
31
32start();

This is the most basic server you can create using Hapi.

We start as usual by requiring Hapijs dependency and create a new object with a configuration of our own. See the host and port above.

After that, we add a simple route that uses HTTP method GET and has a handler function or usually called a callback function to return the response back to the client when a request comes in. Lastly, we are creating an asynchronous function to bootstrap the server using async/await syntax.

The async/await requires you to add a try/catch block every time you want to catch the errors. We console.log in case any error occurs running the program and use Nodejs global process object to make sure that program exits gracefully in case of one. To see it in action, run node server.js and it will eventually run on port 8000.

Setting up a React app

🔗

Now that we have built our server, let us create the front end of our application. We have already installed the main ingredient we need to start with. Open your terminal and type:

create-react-app client

This will create a react application named client inside the folder where we previously built our server. Simple as that.

Now you can traverse to the client directory and run the React app separately on a different port. However, this is not what we want.

The proxy

🔗

We want a setup that will make our React app and use the server URL as a global variable. This is easier than you might think.

Navigate to client directory and locate package.json file. Add the following configuration to it.

And that’s it. This is all you need to do. But wait! How is this even possible? The answer lies with the create-react-app.

create-react-app does all this automatically and behind the scene because it is using webpack.

Webpack has a development server that uses a proxy to handle the API server or in other terms, it requests to our Hapi server running on port 8000. This is one of the biggest advantages I have found for using create-react-app so far. Webpack handles all the configuration.

Conclusion: Running the app

🔗

Let us now test a route that sends the data from the Hapi backend server to React front-end side whenever a request comes from the client. Create a route /mockin server.js to serve the data the dummy data defined as an array data itself.

1'use strict';
2
3const Hapi = require('hapi');
4
5// mock data
6
7const data = [
8 { id: 1, name: 'Alex', age: 21 },
9 { id: 2, name: 'Alice', age: 23 }
10];
11
12// Create a server with a host and port
13const server = Hapi.server({
14 host: 'localhost',
15 port: 8000
16});
17
18// Add the route
19server.route({
20 method: 'GET',
21 path: '/',
22 handler: (request, h) => {
23 return 'hello world';
24 }
25});
26
27server.route({
28 method: 'GET',
29 path: '/mock',
30 handler: (request, h) => {
31 return { data };
32 }
33});
34
35// Start the server
36async function start() {
37 try {
38 await server.start();
39 } catch (err) {
40 console.log(err);
41 process.exit(1);
42 }
43
44 console.log('Server running at:', server.info.uri);
45}
46
47start();

To test this route, let us use REST client like POSTMAN or Insomnia and see if the data is being requested at the route /mock.

Now let us display this data in our front end. Traverse to client/App.js file and do the following.

1import React, { Component } from 'react';
2import logo from './logo.svg';
3import './App.css';
4
5class App extends Component {
6 state = {
7 data: []
8 };
9
10 componentDidMount() {
11 this.fetchData()
12 .then(res => this.setState(res))
13 .catch(err => console.log(err));
14 }
15
16 fetchData = async () => {
17 const response = await fetch('/mock');
18 const body = response.json();
19
20 return body;
21 };
22
23 render() {
24 return (
25 <div className="App">
26 <header className="App-header">
27 <img src={logo} className="App-logo" alt="logo" />
28 <h1>Data from the Backend</h1>
29 {this.state.data.map(person => (
30 <p key={person.id}>
31 Name: {person.name} <br /> Age: {person.age}
32 </p>
33 ))}
34 </header>
35 </div>
36 );
37 }
38}
39
40export default App;

We start by defining a local state that will contain the data coming from the backend inside componentDidMount() life-cycle hook method. This further calls the asynchronous methodfetchData() that actually requests the data from the API url /mock. Since we have already defined the complete URL as proxy we do not have to write the complete url.

Finally, we are able to see the data as below.

You can find the complete source code for the above article at Github Repo

Originally published at Crowdbotics


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.