React (Frontend) - Nodejs (Backend)

Ajith
Nerd For Tech
Published in
8 min readMar 18, 2021
Image from Morioh

Many of us, including me, would have struggled to develop a React app connected to a Nodejs backend! Today, through this article, I will show you the basics of connecting these two, and Bonus !, how to publish the site to Vercel (including the backend and frontend)

I am not going for a chat or other applications, but a small ‘Hello World’ example !

So let’s dive into it…

Prerequisites:

That’s all you need !

Client Side Installation

First of all, install the package ‘create-react-app’ using npm i create-react-app -g in your command-line. (For this tutorial, I am using the Windows CMD).

After the installation, you can go to the folder, where you want to create your front-end ( using the cmd ). In your folder, type npx create-react-app firstapp ( You can change the firstappaccording to your wish )

Installing the app

After the installation, type cd firstapp then code . This will open the VSCode. ( You can use your preferred code editor. I will be using VSCode for now ).

Now comes the cleaning process. In your project’s root. you can go to the src folder. Inside it, you may delete the App.test.js and setupTests.js as these are not needed!

The good news is that we have finished the client-side installation !

Client Side Set-Up

Now, let’s dive into your code. As I said above, I am only going to the ‘Hello-World’ example. For this, let’s navigate to the App.js in the src folder. You may remove all the code inside the <div className="App"> After deleting, add this piece of code to the very top of your (whole) code: import React, { useEffect } from “react"; Now you should have something like:

import React, { useEffect } from "react";
import "./App.css";
function App() {
return <div className="App"></div>;
}
export default App;

Next, inside the the function App() add:

useEffect(() => {
console.log("This only run once!");
}, []);

Now your whole App.js may look like this:

App.js

By using UseEffect Hook, you tell React that your component needs to do something after render. React will remember the function you passed ( and call it later after performing the DOM updates.

Next, let’s run the app by going to the Terminal > New Terminal in VSCode. In the terminal type npm start . This will open localhost:3000 for our development. Now you may see, in your browser’s console, ‘This only run once!’ printed !

You may close the development server by pressing Ctrl + c then hitting enter in the terminal!

Next step is to install axios . Even though, it is not needed now, we are going to complete it. Open a new terminal and type npm i axios . After the installation is complete, navigate to the src folder and create a new file called axios.js . Inside it, add this piece of code:

import axios from "axios";  //imports axiosconst instance = axios.create({
baseURL: "/",
});
export default instance; //exports the instance

Here, we are setting the axios baseURL as ‘/’ . For example, if our website’s link is ‘www.firstapp.com’ then the baseURL would be ‘www.firstapp.com/’. You will get the idea, as we set up the server-side also!

As, I already said, this is not important for now, but we need it anyway!

The good news is that we have finished the client-side set-up !

Server Side Installation

Navigate to the root of your project. Create a new folder called api. Now, in your terminal, navigate to the api folder by cd api . Then in the terminal, type npm init . This will create us a package.json . This may ask us a few questions. But the important one is the entry-point . For that question, just type server.js . For others, just hit the enter.

npm init

Now, in your backend folder ( api folder ) you may see a package.json . The content of it should be like this:

package.json (initial)

Now let’s make some changes !

Create a new terminal. Type cd api then npm i nodemon --save-dev . After this process, navigate to your package.json. Add this line, inside the "scripts"

"start": "nodemon server.js"

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

Next is to add a .gitignore file in your backend ( api folder ). Inside the .gitignore file, add:

/node_modules

A gitignore file specifies intentionally untracked files that Git should ignore.

The good news is that we have finished the server-side installation !

Server Side Set-Up

Lets’ dive into our Server-side set up.

Firstly, let’s install express . In your terminal, navigate to the api folder. Type npm i express --save .

Then, you may create a server.js file in the backend ( api folder ). Inside the server.js add these:

const express = require("express");  //requires (imports) the               //express packageconst PORT = process.env.PORT || 5000;  //see below
const server = express();
server.listen(PORT, () => console.log(`listening on port ${PORT}`));

process.env.PORT || 5000 means: whatever is in the environment variable PORT, or 5000 if there’s nothing there.

Now in the terminal ( in the api folder ) type npm start . You may see:

Now, you can close the server ( by pressing Ctrl + c then hitting enter key ).

In your server.js , before the server.listenadd:

server.use(express.json());
server.use(express.urlencoded({ extended: true }));

The express.json() parses incoming requests with JSON payloads and is based on body-parser.

The express.urlencoded() is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

Just below, add:

server.get("/api/hello", (req, res) => {
res.status(200).send("Hello World!");
});

When a Request is made to ‘/api/hello’ , the server will send, as the response, “Hello World” also set the response status as 200.

Now the server.js will look like:

server.js
const express = require("express");const PORT = process.env.PORT || 5000;const server = express();
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.get("/api/hello", (req, res) => {
res.status(200).send("Hello World!");
});
server.listen(PORT, () => console.log(`listening on port ${PORT}`));

Let’s test your simple server. Just type, (in the api folder), npm start . Then in your browser, go to http://localhost:5000/api/hello.

That’s it! ( you may close the server for now! )

The good news is that we have finished the server-side set up !

Connecting Front-end and Back-end

Go to your frontend package.json . Inside it add:

"proxy": "http://localhost:5000/",

For telling the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json. For more info: https://create-react-app.dev/docs/proxying-api-requests-in-development/

Next, you want your backend and frontend running at the same time! For that you may need the package npm-run-all . Install it in the frontend of your project by npm i npm-run-all --save-dev . After the installation, you have to make some changes in your frontend package.json . Change all of the code in the "scripts" in the package.json to:

"start": "run-p start:**",
"start:app": "react-scripts start",
"start:server": "cd api && npm start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"now-build": "react-scripts build && mv build dist"
package.json

Now in the terminal, (in the root of your project) start your project by npm start

That’s It !

Now, in your src > App.js :

import axios from "./axios";//rest of the code ...useEffect(() => {
axios.get("api/hello").then((response) => {
console.log(response.data);
});
}, []);

After this, your App.js will look like:

import React, { useEffect } from "react";
import "./App.css";
import axios from "./axios";
function App() {
useEffect(() => {
axios.get("api/hello").then((response) => {
console.log(response.data);
});
}, []);
return <div className="App"></div>;}export default App;

Now, in your code, you may see axios.get("api/hello") . Here, there is no need of ‘/’ before the “api” as I said in the Client Side Set-Up.

The good news is that we have finished connecting the front-end and back-end!

Showing the Result in the UI

The last and final step is to show the result of the fetch in the UI. For that, rewrite the App.js to:

import React, { useEffect, useState } from "react"; 
import "./App.css";
import axios from "./axios";
function App() {
const [result, setResult] = useState("");
useEffect(() => {
axios.get("api/hello").then((response) => {
setResult(response.data);
});
}, []);
return <div className="App">
{result && <h1>{result}</h1>}
</div>;
}export default App;

In the first line, we added the code to import useState from ‘react’. Then we created a new State called ‘result’. After when the fetch is completed, we set the ‘result’ as the response.data ( which is the “Hello World” from the server code ). Then a h1 tag to display the result in the UI

The good news is that we have finished showing the result in the UI !

Publishing To Vercel

Before we could publish the app to Vercel, we need to create configuration file for Vercel. We add that file in the root of your project and should be named vercel.json . Inside it add:

{"version": 2,"public": false,"builds": [
{ "src": "package.json", "use": "@vercel/static-build" },
{ "src": "/api/server.js", "use": "@vercel/node" }
],
"rewrites": [
{ "source": "/api/(.*)", "destination": "/api/server.js" },
{ "source": "(.*)", "destination": "/index.html" }
]
}

For more info for the vercel.json , please visit https://vercel.com/docs/configuration

Now let’s dive into the production part ! ( You should meet the prerequisites mentioned above for this step )

Using the terminal, in the root of your project, type vercel --prod .

This will promote your site to production and will ask some questions and the answers you provide must be:

You can go to the link given as ‘production’. That’s it

The good news is that we have finished publishing your site !

That’s all for today ! If you got bored reading this article, find this interesting tip: How the name ‘Github’ was formed ? By joining the letters ‘G-i-t-h-u-b’. That’s it ! The good news is that we have finished reading my little joke !

If you haven’t read my next(from future) article, find it here.

Hope all of you like this !

Thanks!

--

--