How to Create a React App with a Node Backend

This guide is designed to help you create full-stack projects with React as easily as possible.

Let's see how to set up an entire project using React and Node from scratch.

ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable UI components. It is an open-source, component-based front end library which is responsible only for the view layer of the application. It was initially developed and maintained by Facebook and later used in its products like WhatsApp & Instagram.

The main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. It uses virtual DOM (JavaScript object), which improves the performance of the app. The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS on the client and server-side as well as with other frameworks. It uses component and data patterns that improve readability and helps to maintain larger apps.

Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!

Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.

A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.

This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.

Tools You Will Need

  1. Make sure Node and NPM are installed on your computer. You can download both at nodejs.org (NPM is included in your Node installation)
  2. Use a code editor of your choice.

Step 1: Create your Node (Express) backend

First create a folder for your project, called react-node-app (for example).

Then, drag that folder into your code editor.

To create our Node project, run the following command in your terminal:

npm init -y

This will create a package.json file which will allow us to keep track of all our app scripts and manage any dependencies our Node app needs.

Our server code will live in a folder of the same name: server. Let's create that folder.

In it, we'll place a single file, out of which we'll run our server: index.js.

We'll use Express to create a simple web server for us which runs on port 3001 if no value is given for the environment variable PORT.

// 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 in our terminal, we will install Express as a dependency to use it:

npm i express

After that, we will create a script in package.json that will start our web server when we run it with npm start:

// server/package.json

...
"scripts": {
  "start": "node server/index.js"
},

Finally, we can run our app using this script by running npm start in our terminal and we should see that it is running on port 3001:

npm start

> node server/index.js

Server listening on 3001

Step 2: Create an API Endpoint

We want to use our Node and Express server as an API, so that it can give our React app data, change that data, or do some other operation only a server can do.

In our case, we will simply send our React app a message that says "Hello from server!" in a JSON object.

The code below creates an endpoint for the route /api.

If our React app makes a GET request to that route, we respond (using res, which stands for response) with our JSON data:

// server/index.js
...

app.get("/api", (req, res) => {
  res.json({ message: "Hello from server!" });
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

Since we've made changes to our Node code, we need to restart our server.

To do that, end your start script in the terminal by pressing Command/Ctrl + C. Then restart it by running npm start again.

And to test this, we can simply visit http://localhost:3001/api in our browser and see our message:

Step 3: Create your React frontend

After creating our backend, let's move to the frontend.

Open another terminal tab and use create-react-app to create a new React project with the name client:

npx create-react-app client

After that, we will have a React app with all of its dependencies installed.

The only change we have to make is to add a property called proxy to our package.json file.

This will allow us to make requests to our Node server without having to provide the origin it is running on (http://localhost:3001) every time we make a network request to it:

// client/package.json

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

Then we can start up our React app by running its start script, which is the same as our Node server. First make sure to cd into the newly-created client folder.

After that, will start up on localhost:3000:

$ cd client
$ npm start

Compiled successfully!

You can now access your application at http://localhost:3000

Step 4: Make HTTP Requests from React to Node

Now that we have a working React app, we want to use it to interact with our API.

Let's see how to fetch data from the /api endpoint that we created earlier.

To do so, we can head to the App.js component in our src folder and make an HTTP request using useEffect.

We will make a simple GET request using the Fetch API to our backend and then have our data returned as JSON.

Once we have the data returned to us, we will get the message property (to grab our greeting that we sent from the server) and then put it in a state variable called data.

This will allow us to display that message in our page if we have it. We are using a conditional in our JSX to say that if our data is not there yet, show the text "Loading...".

// 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;

Leave a Reply

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

*
*
*