Building a REST API with Node.js and Express for a React App | asadmukhtar.info
Step-by-Step Guide to Setting Up Authentication in Laravel 12 with Breeze   |   Manual Authentication in Laravel 12: Step-by-Step Guide   |   How to Build a REST API in Laravel 12 with Sanctum   |   Laravel 12 CRUD Application with Image Upload   |   Laravel 12 Multi-Auth System: Admin & User Login   |   How to Integrate Stripe Payment Gateway in Laravel 12   |   Building a Role-Based Access Control (RBAC) in Laravel 12   |   How to Use Laravel 12 Queues and Jobs for Background Tasks   |   Laravel 12 Livewire CRUD Example with Validation   |   Email Verification and Password Reset in Laravel 12   |   How to Use Laravel 12 API with Vue.js 3   |   Laravel 12 AJAX CRUD with jQuery and Bootstrap   |   Laravel 12 Multi-Language Website Setup   |   React Best Practices for 2025: Performance, SEO, and Scalability   |   How to Build a Full-Stack MERN App: A Step-by-Step Guide   |   React State Management: Redux vs. Context API vs. Recoil   |   Server-Side Rendering (SSR) in React with Next.js for SEO   |   How to Optimize React Apps for Faster Load Times   |   Building a REST API with Node.js and Express for a React App   |   Integrating JWT Authentication in React and Node.js (MERN Stack)   |   Real-time Chat App with React, Node.js, and Socket.io   |   How to Deploy a MERN Stack Application on AWS or Vercel   |   Connecting React Frontend to a Node.js Backend with Axios   |   Laravel Implement Flash Messages Example   |   How to integrate Angular 19 with Node.js and Express for full-stack development   |   Best practices for connecting Angular 19 frontend with Laravel API   |   Step-by-step guide to upgrading an existing project to Angular 19   |   How to implement authentication in Angular 19 using JWT and Firebase   |   Optimizing server-side rendering in Angular 19 with route-level render modes   |   Using Angular 19 signals for state management in large applications   |   How to create standalone components in Angular 19 for modular architecture   |   Building a CRUD application in Angular 19 with MongoDB and Express   |   Implementing lazy loading in Angular 19 to improve performance   |   How to integrate Angular 19 with GraphQL for efficient data fetching   |   Vue 3 Composition API vs Options API: A Comprehensive Comparison   |   Fetching and Displaying Data from APIs in Vue.js with Axios   |   Building a Todo App in Vue.js with Local Storage Integration   |   Handling Forms and Validation in Vue.js Using VeeValidate   |   State Management in Vue.js Applications Using Vuex   |   10 Most Important Tasks Every MERN Stack Developer Should Master   |   How to Build a Full-Stack CRUD App with MERN Stack   |   Best Practices for Authentication & Authorization in MERN Stack   |   1. MEAN Stack vs. MERN Stack: Which One Should You Choose in 2025   |   Top 10 Node.js Best Practices for Scalable and Secure Applications   |   How to Build a REST API with Laravel and Node.js (Step-by-Step Guide)   |   Mastering Angular and Express.js for Full-Stack Web Development   |   Top 10 Daily Tasks Every Frontend Developer Should Practice   |   Essential Backend Development Tasks to Boost Your Coding Skills   |   Real-World Mini Projects for Practicing React.js Daily   |   Laravel Developer Task List: Beginner to Advanced Challenges   |   How to Assign Effective Tasks to Your Intern Developers   |   10 Must-Try Tasks to Master JavaScript Fundamentals   |   Practical CSS Challenges That Improve Your UI Design Skills   |   Top Tasks to Learn API Integration in React and Angular   |   Best Task Ideas for a 30-Day Web Development Challenge   |   Top Git and GitHub Tasks Every Developer Should Know   |   30-Day Task Plan for Web Development Interns   |   Weekly Task Schedule for Junior Developers in a Startup   |   How to Track Progress with Development Tasks for Interns   |   What Tasks Should You Give to Interns in a MERN Stack Project   |   Build These 5 Projects to Master React Routing   |   Task-Based Learning: Become a Full-Stack Developer in 90 Days   |   Daily Coding Tasks That Will Sharpen Your Logical Thinking   |   Top 7 Backend Task Ideas to Practice With Node.js and MongoDB   |  

Building a REST API with Node.js and Express for a React App

In modern web development, creating a REST API to handle data interactions between a backend server and a frontend application is crucial. With React as the frontend and Node.js/Express as the backend, you can create a dynamic web application capable of fetching and sending data to the server. This tutorial will walk you through building a simple REST API with Node.js and Express and integrating it with your React application.

We’ll cover the setup of a basic Node.js backend that will handle routes and communicate with a React app to perform CRUD (Create, Read, Update, Delete) operations. By the end of this guide, you'll have a fully functioning app where the React frontend interacts with the backend through API calls.

1. Setting Up the Backend with Node.js and Express

What is Node.js and Express?

Node.js is a runtime environment that allows you to run JavaScript on the server-side, while Express is a lightweight framework built on top of Node.js for building APIs and web applications.

Steps to Set Up the Backend:

  1. Install Node.js and NPM:

    • Ensure that you have Node.js installed. You can download it from nodejs.org.
    • Use npm (Node Package Manager) to install required packages.
  2. Initialize a New Node.js Project: Run the following command to initialize a new project:

mkdir my-node-backend
cd my-node-backend
npm init -y

Install Express: Install Express by running:

npm install express

Create a Basic Server: Create a file named server.js and set up a basic Express server:

const express = require('express');
const app = express();
const port = 5000;

app.use(express.json()); // for parsing application/json

app.get('/', (req, res) => {
  res.send('Hello from the Node.js server!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Start the Server: Run the server using:

node server.js
  1. Now, your backend server should be running at http://localhost:5000.

2. Creating Routes for the API

What is an API Route?

An API route is where your React frontend will send HTTP requests (GET, POST, PUT, DELETE) to perform CRUD operations. These routes are defined in your Express app.

Steps to Create Routes:

  1. Define Basic API Routes in Express: Add routes to handle CRUD operations for a resource (e.g., users):

let users = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Smith' }
];

// GET all users
app.get('/api/users', (req, res) => {
  res.json(users);
});

// POST a new user
app.post('/api/users', (req, res) => {
  const newUser = req.body;
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT to update a user
app.put('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const updatedUser = req.body;
  const userIndex = users.findIndex(u => u.id === userId);

  if (userIndex !== -1) {
    users[userIndex] = { id: userId, ...updatedUser };
    res.json(users[userIndex]);
  } else {
    res.status(404).send('User not found');
  }
});

// DELETE a user
app.delete('/api/users/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  users = users.filter(user => user.id !== userId);
  res.status(204).send();
});

3. Setting Up the React App to Make API Calls

What is an API Call?

An API call allows your frontend (React) to communicate with the backend server to fetch or send data.

Steps to Set Up React:

  1. Create a React Application: Use Create React App to initialize a new React project:

npx create-react-app my-react-frontend
cd my-react-frontend

Install Axios for HTTP Requests: Axios is a promise-based HTTP client that helps make API requests from React:

npm install axios

      2. Make API Calls from React: In your React app, create components that interact with the backend API.

For example, create a UsersList component to display users fetched from the backend:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const UsersList = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('http://localhost:5000/api/users')
      .then(response => {
        setUsers(response.data);
      })
      .catch(error => console.error('There was an error fetching the users!', error));
  }, []);

  return (
    <div>
      <h1>Users List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default UsersList;

Run Your React App: Start the React app:

npm start

4. Connecting the Frontend and Backend

Now that you have both your frontend (React) and backend (Node.js/Express) set up, you can send data between them.

Steps to Make POST Requests:

  1. Create a Form in React to Add Users: Allow users to submit data to the backend via a form

const AddUser = () => {
  const [name, setName] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const newUser = { id: Date.now(), name };

    try {
      await axios.post('http://localhost:5000/api/users', newUser);
      alert('User added successfully!');
    } catch (error) {
      console.error('Error adding user:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Enter name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button type="submit">Add User</button>
    </form>
  );
};
  1. Post Data from React to Backend: Use Axios to send a POST request to the backend when the form is submitted. The new user will be added to the backend, and the frontend will update automatically.

5. Testing the Full App

  1. Test Backend: Test the REST API directly by making requests to the backend using tools like Postman or Insomnia to verify that the routes work correctly.

  2. Test Frontend: Make sure the React app is able to fetch data and interact with the backend. Test by adding, deleting, and updating users.

Conclusion

Building a REST API with Node.js and Express for a React app is an essential skill in modern web development. By creating a backend API and linking it with the frontend React application, you enable users to interact dynamically with the application. This setup allows for CRUD operations, making your app functional and interactive.

With Express handling the backend and Axios facilitating HTTP requests in React, you now have a basic full-stack application. By following the steps outlined, you can expand your app’s functionality by adding authentication, validation, or advanced data handling.


Related Tutorials

How to Build a Full-Stack MERN App: A Step-by-Step Guide
Building a REST API with Node.js and Express for a React App
Integrating JWT Authentication in React and Node.js (MERN Stack)
Real-time Chat App with React, Node.js, and Socket.io
How to Deploy a MERN Stack Application on AWS or Vercel
Connecting React Frontend to a Node.js Backend with Axios
10 Must-Try Tasks to Master JavaScript Fundamentals