How to integrate React frontend with Node backend
Tags: javascript, react, node, express
Published: 2021-05-02 03:59:55

## Overview :

React framework is great for creating awesome web apps and UIs. But sometimes we need extra functionalities like integrating database or performing authentication. Such stuff needs to be done in backend, you don't want that anyone can see your secret keys or hashing stuff in frontend.

That's why in this article we are going to learn how to connect your React frontend with express backend. Sometimes this task get really overwhelming, you might get stuck with CORS issue, we will be handling all of them in this one article.

Our motive is to create a server that host an API and then we make a GET request from React frontend and display the data on screen.

## Prerequisites : 

![](https://media.giphy.com/media/TGvHZanK0Y8poe2lnA/giphy.gif)


- Basic React knowledge and comfortability with environment.
- Basic Express knowledge.

## Let's get going 👍

First of all create a folder and call it anything, we are naming it as `app`. This folder will contain all our frontend + backend code.

Now we will start with creating backend first, 

## Setting up Server

Open the terminal and locate to your `app` folder. Now inside this folder we will create `server.js` file. Yeah exactly this file will contain code responsible for server running and API hosting.

![Screenshot 2021-05-01 at 8.26.58 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619868185288/Roiq4kTz0.png)

now we are going to initialize `npm` in this folder to handle external packages and dependencies.
In the terminal type `npm init -y` it will initialized the npm with default values.


![Screenshot 2021-05-01 at 8.28.16 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619868607424/Kt0s6rWhe.png)

As a result you will see a file with name `package.json` will automatically get created.

From this step we are going to handle rest of the things on your favourite code editor. I am using VSCode in this article.
Open `app` folder on VSCode.

Now we have to install some packages, these are
- `express`
- `cors`

I hope you are familiar with `express` it's a widely used module for maintaining backend. Now what is the use of `cors` library, okay so for this first we need to understand what CORS really is.


![](https://media.giphy.com/media/SvRuvlSEa67wNNHuHy/giphy.gif)


CORS is shorthand for Cross-Origin Resource Sharing. It is a mechanism to allow or restrict requested resources on a web server depend on where the HTTP request was initiated.
Whenever we make request to a server we send a header called `origin`. It contain the information about from where the request is originated and using this header a web server can restrict or allow the resource sharing between client and server.

> By default requests from any other origins will be restricted by the browser.

If you want to read more about CORS, here's the link you can refer to [More on CORS](https://stackabuse.com/handling-cors-with-node-js/) 

Now with the use `cors` middleware we can allow CORS for all routes or to some specific routes, in this article we will allow for all routes but if you want to read more then refer to  [cors documentation](https://www.npmjs.com/package/cors).

For installing above packages open terminal in your VSCode and type following `npm install express cors`.

![Screenshot 2021-05-01 at 8.34.42 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619869832446/x3vqaVeP4.png)

Now all left is to setup our backend server, ***coding time***  🥳

Let's start with creating a file `data.js`. This file will contain our API data that we are going to host and then we `export` the API data so that we can use it inside our `server.js`.

![Screenshot 2021-05-01 at 8.50.32 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619870377567/p-Uc9Xomv.png)

Okay now let's setup our server, open the `server.js` and follow the below image

![Screenshot 2021-05-01 at 8.50.07 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619870409477/IALSsR5zp.png)

As you can see that the code is self explanatory but still I want to highlight a point that is ***port number on which our server is listening***

Take any free port number you want *except* `3000` why? because `port 3000` is used by react frontend and if you use same for your backend then it might gonna crash. Here you can see I used `port 5000`.

Now let's test if our server is working or not. Open the terminal again and type following `node server.js` and in the console you can see it'll be printing `server is running on port 5000`.

![Screenshot 2021-05-01 at 8.51.02 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619870764377/ZSKBoWnuSl.png)

Open your browser and go to the following URL `http://localhost:5000/api`

You can see your API data there in JSON format. For better visualization you can use extensions like ***JSON viewer pro*** here's the link for  [download](https://chrome.google.com/webstore/detail/json-viewer-pro/eifflpmocdbdmepbjaopkkhbfmdgijcc).


![Screenshot 2021-05-01 at 8.53.35 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619870961195/iSlHycNd7.png)

YAYYYY 🎉...  Our server is up and running.

Time to move to frontend and start building it.

## Setting up React frontend

First of all make a folder `client`, this will contain our frontend stuff.

![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619871668711/3ufxPI7br.png)

Now go inside the `client` folder and type the following on terminal `npx create-react-app my_app`

![2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619872012141/nGJSw6BK_.png)

It'll take some time to process and when it done you'll see a folder named `my_app` created, see below

![3.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619872220355/9CIFW2sIm.png)

Now inside the VSCode you can see that `client/my_app` will contain some pre-build files they all are the initial setup for React frontend. You can modify them as the way you want, but in this article we just modify `package.json` and `App.js` to our need.

Now open the `package.json` from the `client/my_app` folder on VSCode and add the following property below `private: true` property. 

`proxy: "http://localhost:5000"`

see below for reference

![5.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619872462547/rZa9r4Bah.png)

Now adding this property makes React to use `http://localhost:5000` as default URL for making requests.

It's time to setup `App.js` to make request to our server and render data on client's screen.
Open `App.js` on VSCode and in the function `App` delete everything inside the `div having class  'App'` and do the following.


![6.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619872833443/w4OlDZQhx.png)

As you can see the code is self explanatory but still I again want to highlight a point that, just take a look at the `fetch("/api")`. You can notice we are not providing complete endpoint like `http://localhost:5000/api` and the reason is ***we don't need to*** remember the `proxy` property we set earlier. All credit goes to it, now we can create as many routes we want inside your server and can access them in React with similar manner.

Now open terminal inside VSCode and select a new `zsh` or `bash` whatever you prefer and make sure you are inside the`my_app` folder.

![7.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619873125531/sl8dVP0Th.png)

and when you are in, type following in terminal to start the React frontend server. `npm start`

![9.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619873533809/quItnVM8I.png)

> ignore all the warnings for now

This command will basically compile your React code and start the server at `port 3000`. It will also automatically open your web browser and get located to `http://localhost:3000` and what you can see is a big **" Hello World " ** on screen.

![10.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619873614437/FtfxvMoNZ.png)

Open the `Developers tools` inside brower and in console you can see that our API data is logged there successfully.

![11.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619873706248/TxmWBHA7p.png)

Now we are sure that our frontend is working properly and data is also fetched without any problem, so it's time to render the data on screen. Open `App.js` on VSCode and replace the already written code with the highlighted part of code.

![Screenshot 2021-05-01 at 7.46.46 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619878646161/rsjtTAwfT.png)

As you can notice we just replaced the ***console logging*** and ***Hello World*** to the other code so that it can set the `state` value to ***data*** array and render it on screen with some styling. 

Now just save it and open your browser again to see the final result.

![Screenshot 2021-05-01 at 7.48.38 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619878726691/3zjGdH6HF.png)

If you want to re-check just modify the data inside `data.js` from backend and save it, the modified result will also be displayed on your screen.

***YAYYYYYY...... 🎉 🥳*** our backend and frontend are now perfectly connected, now you can use your backend for integrating database or authentication without any worries of exposing private data on frontend.


![](https://media.giphy.com/media/WueGYCBT6OPsjUMj1J/giphy.gif)


## What's next !

**If you are still reading, make sure to follow me on  [Twitter](https://twitter.com/_s_w_a_y_a_m_)  and subscribe to my newsletter for more as I have some exciting stuff coming up every weekend. See Y'all next time and stay safe ^^ 🌻**