1️⃣ Introduction to Backend for React

Why React Apps Need a Backend Server

Why React Apps Need a Backend

React runs in the browser (client-side). It cannot:

💡 Key Insight: Everything in the browser is visible to users. You need a backend server to handle sensitive operations securely.

The Client-Server Architecture

┌─────────────────┐ HTTP Request ┌─────────────────┐ │ │ ─────────────────────────► │ │ │ React App │ (JSON data) │ Node.js │ │ (Browser) │ │ Server │ │ │ ◄───────────────────────── │ │ └─────────────────┘ HTTP Response └────────┬────────┘ Frontend (JSON data) │ │ ▼ ┌─────────────────┐ │ Database │ │ (MongoDB) │ └─────────────────┘

API Concept (REST & JSON)

What is an API?

API (Application Programming Interface) - A way for programs to communicate with each other. Think of it as a waiter in a restaurant: you tell the waiter what you want, and they bring it from the kitchen.

REST API

REST (Representational State Transfer) uses HTTP methods to perform actions on resources:

HTTP Method Action Example URL Description
GET Read /api/products Get all products
POST Create /api/products Add a new product
PUT Update /api/products/1 Edit product #1
DELETE Delete /api/products/1 Remove product #1

JSON (JavaScript Object Notation)

The standard format for sending data between frontend and backend:

// JSON Response from API
{
  "id": 1,
  "name": "iPhone 15",
  "price": 999,
  "inStock": true,
  "categories": ["electronics", "phones"]
}
// Array of products
[
  { "id": 1, "name": "Laptop", "price": 999 },
  { "id": 2, "name": "Phone", "price": 699 },
  { "id": 3, "name": "Tablet", "price": 499 }
]

Overview of MERN Stack

MERN is a popular full-stack JavaScript solution:

Letter Technology Role Description
M MongoDB Database Stores data as JSON-like documents
E Express.js Backend Framework Handles HTTP requests, routing
R React Frontend Library Builds the user interface
N Node.js Runtime Runs JavaScript on the server
┌────────────────────────────────────────────────────────────────────┐ │ MERN Stack │ ├────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ React │───►│ Express │───►│ Node.js │───►│ MongoDB │ │ │ │ Frontend │◄───│ API │◄───│ Runtime │◄───│ Database │ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ Browser Server Server Cloud/Local │ │ │ └────────────────────────────────────────────────────────────────────┘

Why MERN?

How React Communicates with Backend

// React component fetching data from Node.js API
import { useState } from 'react';

function ProductList() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(false);

  // Async function to fetch data from our Node.js backend
  async function fetchProducts() {
    setLoading(true);
    try {
      const response = await fetch('http://localhost:3000/api/products');
      const data = await response.json();
      setProducts(data);
    } catch (error) {
      console.error('Error fetching products:', error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <button onClick={fetchProducts}>
        {loading ? 'Loading...' : 'Load Products'}
      </button>
      
      {loading && <p>Loading...</p>}
      
      <ul>
        {products.map(product => (
          <li key={product.id}>
            {product.name} - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}
🎯 Summary:
  • React handles the UI (what users see)
  • Node.js handles the logic (data, security, business rules)
  • They communicate via REST API using JSON
  • MERN stack gives you JavaScript everywhere