Basics of Backend and Connecting React Project with Node + Express

Basics of Backend and Connecting React Project with Node + Express

Beginner Friendly

Hi Reader!

Introduction

I wrote many blogs last year but then stopped due to other things in life and studies, Now think I shouldn’t have stopped and felt the sudden urge on an October Weekend (cozy vibes) with a coffee on my table to write this blog. Let’s begin

(Note: If you are familiar with basic backend and setup, jump directly to react + express section ;)

In my web development journey, I learnt React and built several good projects with it. Following the good-ol roadmap (HTML → CSS → JS → Frontend Framework ( I chose React coz its very popular where I live for jobs ) but after successfully doing this and now having somewhat confidence in my frontend skills, I went on with starting a new project. A Game!

I very excitedly built the frontend with React and Tailwind.

I wanted to make it a full stack game where users can play multiplayer, have an account, etc. But

I didn’t know backend. I researched, watched few backend basic videos and how full stack app works, I got introduced to few concepts. But, my main learning came after I applied those learnings in my game project and built a basic backend server, connected my react with node, express.

Learn by doing for the win! 🙌

Now, I want to share my experience and learnings. I wish I had found a blog like this so kinda making it for my past self or someone who is in the same situation as I was.

Basic Node Express Setup

Before moving onto react, lets clear some basics. In this section I will explain how to start our first Backend Server.

Node.js

“ asynchronous event-driven JavaScript runtime “

In short, Node.js helps us to write JS for backend or outside browser. Now, to use Node, we have to follow few steps:

  1. Go the Node’s official website: https://nodejs.org/en/ and install node.

  2. Create a new folder in our computer. Eg- “MyApp”

  3. Go inside the folder and run this command in terminal.

     npm init
    

    It will ask few things,

    • I gave the name “myApp” and kept hitting enter on other things it asked (those are optional like you can give the description if you want or mention the URL of your git repository).

    • Next, I typed my name in author and after that it asked me “Yes or No” where I typed “yes” to create the package.json file.

  • This will create a “package.json” file in the folder/directory.

    “ It is like a log book to keep records (version, name, etc.) of all the packages or other libraries/ dependencies you are installing in your project. “

  • It does things automatically, we don’t have to type the records manually.

  1. Final step, create a server.js file (any name we can give like app.js, index.js, etc.). This file is our main backend file. This is where, we will create our backend server and handle all the http requests which a server handles.

Creating backend server for our application using Node.js-

// fileName : server.js 
// Example using the http module
const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
    // Set the response headers
    res.writeHead(200, { 'Content-Type': 'text/html' });

    // Write the response content
    res.write('<h1>Hello, Node.js HTTP Server!</h1>');
    res.end();
});

// Specify the port to listen on, for eg- https://localhost:3000
const port = 3000;

// Start the server
server.listen(port, () => {
    console.log(`Node.js HTTP server is running on port ${port}`);
});

But, while working on backend, creating a web server using plain Node.js like above is a bit of a hassle and a framework makes it easy for us.

Express.js

Express.js or Express is a backend framework for writing Node.js backend applications. Just like how React is a frontend framework with HTML, CSS, JS.

Express does all the work and set up for us and helps in creating a backend server quickly using it’s inbuilt methods like app.get(), app.listen(), app.post() etc.

  1. Go to your terminal and install express with npm
npm install express
  • If you observe, after installing express, package.json file will automatically update itself, “express version 4.21.0”.

Below is the code to create a simple backend server using Express.js. Look, how clean and nice it looks from the plain Node.js server code.

//server.js
import express from 'express';

const app = express();
const port = 3000;

app.get("/", (req, res) => {
    res.send("Hello World");   
})

app.listen(port, () => {
    console.log(`Server is running at ${port}`);
})
  • This will create a server on http://localhost:3000/ and if you go look at it, it will show “Hello World” on the Website.

After this, you can learn more about different kinds of HTTP requests which helps us in doing CRUD operations (Create, Read, Update, Delete) with our web app. For ex - app.get() is for Reading (displaying) , app.post() is Creating new data value in backend, etc.

Connecting index.html with express

  1. we start with setting up basic express set up we learned in above section.
import express from "express";

const app = express();
const port = 3000;

//mounting/starting everytime the server starts the middleware using .use() method
app.use(bodyParser.urlencoded({ extended: true }))

app.get("/", (req, res) => {
  res.send("hello world")
});

/* if there is a form in our website, 
 on submit that form data will be received here in backend */
app.post("/submit", (req, res) => {
  console.log(req.body);
// req.body contains the data object
})

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});
  • The app.use() will set up middleware:

  • Middleware is like a helper or a traffic officer for a computer program. Imagine you're playing a game, and you need to send a letter to someone in the game. Before that letter reaches your friend, it has to go through a helper who checks it, makes sure everything is okay, and then lets it pass.

  • In the same way, middleware in programming is a special helper that sits in the middle of two parts of a program. It checks the information moving between them, sometimes fixing it, blocking it, or adding something before passing it along.

  1. We can set up our own middleware function, but here I will use body parser. We can easily install it with npm.
npm install body-parser
  • What it does is, it parses the data we will get from the client side and decode it. Makes it accessible to us. Now, req.body will show the data in form of object.
import { dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
  • import.meta.url gives the location (URL) of the current JavaScript file.

  • fileURLToPath() function takes that url and converts into a path for our local system.

  • The import dirname() is NodeJS Built-in function to get the directory name of the current file. You can save the above template and copy paste it in future projects, since copy pasting is time saving if we understand the code.

We will use this dirname in sending the index.html file back to client side. We are on server side right now, pretty cool, right? Backend feels cool.

Backend developer! : r/ProgrammerHumor

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/public/index.html");
});

This is how, our server sends back the html file back to the client when it requests for “/” path, that is “localhost:3000”. Assuming, index.html is inside public folder of your directory.

Now, you can have your index.html as regular html file with css link inside it and js script in body and voila! Your basic full stack app is done (except database right now).

But, how to connect my React App with backend?

Okay, the above part was for normal Html, CSS, JS stuff. But, what about React?

The flow and template is almost same with slight difference.

React + Express

Let’s get started!

  1. First, we need to create static files from our react app. This is stupidly easy with just one command, which places the final app into the dist folder
npm run build
  • When we use this command, all the final, optimized files are put into a folder, often called dist

  • Our express server will serve these static files from dist folder whenever client/user requests them. The React app is then rendered in the browser.

The Code below is the final piece to connect our React Frontend with Express backend.

//index.js or server.js
import express from "express";
import bodyParser from "body-parser";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

// Properly set __dirname in ES module
const __dirname = dirname(fileURLToPath(import.meta.url));

const app = express();
const port = process.env.PORT || 3000;

// Middleware to parse URL-encoded data
app.use(bodyParser.urlencoded({ extended: true }));

// Serve static files from the 'dist' directory (including the assets folder)
app.use(express.static(join(__dirname, "dist")));

// Serve the index.html file from the dist directory
app.get("/", (req, res) => {
    res.sendFile(join(__dirname, "dist", "index.html"));
});

//catch-all route for any unknown paths
app.get("*", (req, res) => {
    res.sendFile(join(__dirname, "dist", "index.html"));
})

// Start the server
app.listen(port, () => {
    console.log(`Server started on port ${port}`);
});
  1. express.static(): This is a middleware function that tells the server to serve all the files inside the dist folder.
// Serve static files from the 'dist' directory (including the assets folder)
app.use(express.static(join(__dirname, "dist")));
  • Notice I didn’t do any routing assuming that in most react apps, client-side routing is there, for eg- React Router Dom. That’s why on each HTTP request, we are sending back our static html file and by this, internal client side routing takes over.

That’s it, Now, simply run the index.js file (our main backend file), and on our local host we can see our react web app.

Thank you for reading till end and I hope there was some learnings and value you can take away from this blog. Maybe, ig bookmark it and refer it whenever you want to start your backend server.

I will keep writing more about my tech experiences and learnings in future.

Happy Coding! 💻