How to Build a React App Using Node Back-end? A Comprehensive Guide

by Developers for Hire
0 0
Read Time:8 Minute, 3 Second

Building a React app with a Node.js back-end opens a world of possibilities for creating dynamic and robust web applications. The server-side prowess of Node.js and the front-end capabilities of React together empower you to build applications that respond quickly and efficiently to user interactions.

We will start this blog with a step-by-step approach, guiding you through setting up a development environment, including installing Node.js and setting up a React project. Next, we’ll delve into the core concepts of React, covering component creation, state management, and data flow while simultaneously exploring the creation of a Node.js back-end.

By the end of this guide, we hope you gain a good knowledge of building a powerful app using React and Node integration. So, without wasting much time, let’s start now!

Prerequisites

Before you start to build React app with a Node back-end, it is essential to ensure you have the following-

  • Ensure you have Node and Node Package Manager (NPM) installed on your system. You can install both from nodejs.org.
  • You have Visual Studio installed. If not, you can download it from code.visualstudio.com.
  • Install Git on your computer. You can download it from git-scm.com.
  • You need to sign up for an account on heroku.com.

Step-by-Step Process to Building a React App with Node Back-end

Now that you have all the necessary software installed on your system, it’s time to follow the steps to creating a high-end React app with a Node back-end. Carefully read each step to understand the process.

Step 1: Create Node (Express) back-end

Create a new folder with the name – react-node-app.

Move your folder to the visual code editor.

Now, run the below command in your terminal –

"npm init -y"

The command will create a file package.json, which will keep track of all your app scripts and manage dependencies for Node.

Now, create a new folder: Server. Place a single file for running the server: index.js.

Here we will use Express to build a web server for our app. The app runs on port 3031.

// server/index.js

const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

app.listen(PORT, () => {

  console.log(`Server listening on ${PORT}`);

});

Then, install Express as a dependency in your terminal:

npm i express

Following that, we will build a script in the package.json to start our web server on npm:

// server/package.json

...

"scripts": {

  "start": "node server/index.js"

},

...

Now, we can run npm to ensure our app uses the same script. Additionally, you can see it is running on the 3031 port:

npm start

> node server/index.js

Server listening on 3001

Step 2: Create an API Endpoint

In this step, we will use Node and Express servers as APIs. It can give access to our React app data, modification, or so some other operations.

You have to simply send React app a message “Hello from server!” in a JSON object.”

Create an endpoint for the Route/API using the following command:

// server/index.js

...

app.get("/api", (req, res) => {

  res.json({ message: "Hello from server!" });

});

app.listen(PORT, () => {

  console.log(`Server listening on ${PORT}`);

});

The server needs to restart as we make changes in the Node code.

To restart your server, end your start script by pressing Command/Ctrl + C. Restart the server by running the command – npm start again.

To test the server, simply go to the URL http://localhost:3001/api in your browser and see the message.

Step 3: Create your React Front-end

After building the back end of our app, let’s move to create the front end.

First, open a terminal tab and use the command – “create-react-app” to build a new React project with the client name:

Open another terminal tab and type the following command –

npx create-react-app client

Following that, you get a React app with all the installed dependencies.

Now, make a change by adding a property called proxy to the package.json file.

This change will make requests to the Node server without having to provide a local host port every time you make a network request.

// client/package.json

...

"proxy": "http://localhost:3001",

...

Start your React app using the start script, which is the same as the Node server. First, ensure to add a cd to a client folder.

cd client

npm start

Local: http://localhost:3000

Step 4: Send HTTP Requests from React to Node Server

Now that you have built a React app, it’s time to integrate it with APIs.

Here’s how to fetch data from the API endpoint you build in the previous steps.

For this, navigate to the App.js component in your src folder and, using the useEffect, make an HTTP request.

Now, make a GET request with Fetch API to restore data as JSON.

Once you get the restored data, you will receive the message property. Put the message in a state variable.

This will allow you to display the message on your page. Then, use the following command –

// client/src/App.js

import React from "react";

import logo from "./logo.svg";

import "./App.css";

function App() {

  const [data, setData] = React.useState(null);

  React.useEffect(() => {

    fetch("/api")

      .then((res) => res.json())

      .then((data) => setData(data.message));

  }, []);

  return (

    <div className="App">

      <header className="App-header">

        <img src={logo} className="App-logo" alt="logo" />

        <p>{!data ? "Loading..." : data}</p>

      </header>

    </div>

  );

}

export default App;

Step 5: Launch your app with Heroku

Now that you are done with your app’s front-end and back-end, let’s deploy it using Heroku.

First, remove the Git repo file from the client folder. This is an auto-initiated file.

These changes are essential as we will set up the Git repo in the project’s root folder, not in the client. Use the following command –

cd client

rm -rf .git

When our app is ready to go live, we will have both our React front-end and our Node back-end running on the same domain name (for example, mycoolapp.herokuapp.com).

To make sure that our users can see our React app when they visit our app’s home page (or any other page), we need to add some code in server/index.js that will serve our React app whenever it is requested by our user.

The code we need to add in server/index.js is:

// server/index.js

const path = require('path');

const express = require('express');

...

// Have Node serve the files for our built React app

app.use(express.static(path.resolve(__dirname, '../client/build')));

// Handle GET requests to /api route

app.get("/api", (req, res) => {

  res.json({ message: "Hello from server!" });

});

// All other GET requests not handled before will return our React app

app.get('*', (req, res) => {

  res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));

});

This code will enable Node to access the static files of our React project that we have built using Express.static function.

And if our server receives a GET request not for our /api route, it will return our React app.

This code makes it possible for our Node and React apps to be deployed together on the same domain name.

Then we can add a build script to our server package.json file that will build our React app for production:// server/package.json

...

"scripts": {

    "start": "node server/index.js,"

    "build": "cd client && npm install && npm run build"

  },

...

I would also suggest adding a field called “engines”, where you can specify the Node version you use to build your project. This will be useful for deployment.

To determine your Node version, simply run the command “node -v”. Once you have obtained the version number (e.g., 14.15.4), you can then insert it into the “engines” section.:

// server/package.json

"engines": {

  "node": "your-node-version"

}

To deploy our app using Heroku, we must have an account at Heroku.com.

After we log in and see our dashboard, we’ll choose New > Create New App and give a unique name to our app.

Then, we’ll need to install the Heroku CLI on our computer so we can use Git to deploy our app whenever we update it. We can install the CLI by running the following:

sudo npm i -g heroku

After installing the Heroku, login to your account using the login command:

heroku login

Press any key to login to Heroku

After you have signed in, you just need to follow the steps for deploying our app in the “Deploy” tab.

To get started with our project, we need to execute the following four commands: create a new Git repository, add our files to it, commit them, and establish a Git remote for Heroku.

git init

heroku Git:remote -a insert-your-app-name-here

git add.

git commit -am "Deploy app to Heroku"

The last step is to launch our app by using the following command:

git push heroku master

Congratulations! You have successfully built a React app using the Node back-end. Your app is live now!

Conclusion

Above, we have tried our best to put everything we know about building a React app with the Node back-end. Developing an app is hard, so you should take coding classes or courses to understand the process more precisely. Our guide will help you build your first React app without much effort and stress.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

You may also like

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

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