Unit 1: Introduction to Web Development & Frontend with React
Topics:
-
Overview of web development: Frontend vs Backend vs Full-stack
-
HTML, CSS, JavaScript fundamentals
-
Introduction to React.js
-
Components, JSX, props, state
-
Functional vs Class components
-
Event handling & forms
-
-
React Hooks:
useState,useEffect,useRef -
Routing with React Router
-
Basic project: Build a simple React-based website
Practical:
-
Create a multi-page React app (e.g., portfolio or task tracker)
Unit 2: Backend Development with Node.js & Express.js
Topics:
-
Introduction to Node.js and its architecture
-
Setting up Express.js server
-
Routing & middleware
-
RESTful API design
-
Handling JSON requests and responses
-
Error handling in Express
-
Environment variables and configuration (
dotenv)
Practical:
-
Build a simple REST API (e.g., user management with CRUD operations)
Unit 3: Database Management with MongoDB
Topics:
-
Introduction to NoSQL and MongoDB
-
Installing and connecting MongoDB with Node.js
-
CRUD operations using MongoDB
-
Mongoose ODM: Schemas, Models, and Validation
-
Data relationships in MongoDB
-
Query optimization and aggregation basics
Practical:
-
Integrate MongoDB with Express API
-
Build a backend for a small app (e.g., blog or task manager)
Unit 4: Full-Stack Integration & Advanced MERN Concepts
Topics:
-
Connecting React frontend with Express/MongoDB backend
-
Axios or Fetch API for HTTP requests
-
JWT-based authentication and authorization
-
Deployment strategies (Heroku, Vercel, Netlify)
-
State management with Redux or Context API
-
Project structure & best practices
-
Optional: Real-time updates with Socket.io
Practical:
-
Build a full-stack MERN project (e.g., e-commerce app, chat app, or task manager)
-
Deploy the project online
Lab Program 1: React Environment Setup & JSX Basics
Aim:
Set up a React development environment and understand JSX.
Tasks:
-
Install Node.js and create React app
-
Understand JSX syntax
-
Create functional components
-
Render components to the DOM
Unit Covered: Unit 1
Tools: Node.js, React
Lab Program 2: React Components, Props & State
Aim:
Implement component-based architecture in React.
Tasks:
-
Create reusable components
-
Pass data using props
-
Manage state using useState
-
Conditional rendering
Unit Covered: Unit 1
Lab Program 3: React Hooks, Forms & Routing
Aim:
Build a multi-page React application.
Tasks:
-
Form handling in React
-
useEffect and useRef hooks
-
Client-side routing using React Router
-
Navigation between pages
Example: Portfolio or Task Tracker
Unit Covered: Unit 1
Lab Program 4: Node.js & Express Server Setup
Aim:
Create a backend server using Express.js.
Tasks:
-
Setup Express server
-
Create routes
-
Use middleware
-
Send JSON responses
Unit Covered: Unit 2
Tools: Node.js, Express.js
Lab Program 5: RESTful API with CRUD Operations
Aim:
Design and implement a REST API.
Tasks:
-
Create REST endpoints (GET, POST, PUT, DELETE)
-
Handle JSON requests
-
Error handling in Express
-
Use Postman for testing
Example: User management system
Unit Covered: Unit 2
Lab Program 6: MongoDB Integration with Node.js
Aim:
Connect MongoDB with Express backend.
Tasks:
-
Install MongoDB and Mongoose
-
Create schemas and models
-
Perform CRUD operations
-
Input validation
Unit Covered: Unit 3
Lab Program 7: MongoDB Relationships & Aggregation
Aim:
Implement data relationships and aggregation.
Tasks:
-
Reference and embedded documents
-
Populate related data
-
Basic aggregation queries
-
Optimize database queries
Example: Blog with users and posts
Unit Covered: Unit 3
Lab Program 8: React + Backend Integration
Aim:
Connect React frontend with backend API.
Tasks:
-
Fetch data using Axios / Fetch API
-
Display backend data in React
-
Handle loading and error states
-
Environment variable usage
Unit Covered: Unit 4
Lab Program 9: Authentication with JWT
Aim:
Implement secure authentication and authorization.
Tasks:
-
User registration and login
-
Password hashing
-
JWT token generation
-
Protected routes in React
-
Middleware for authorization
Unit Covered: Unit 4
Lab Program 10: Full-Stack MERN Project & Deployment
Aim:
Develop and deploy a complete MERN stack application.
Options:
-
E-commerce app
-
Chat application
-
Task management system
Tasks:
-
Frontend + backend integration
-
State management (Context API / Redux)
-
Optional real-time features using Socket.io
-
Deploy frontend and backend
-
Project documentation
Unit Covered: Unit 4
Outcome: Capstone Project 🌟
LAB 1
🔹 Lab Program 1: React Environment Setup & JSX Basics
🎯 Aim
Set up a React development environment and understand JSX fundamentals.
✅ 1. Install Node.js & Create React App
Step 1: Install Node.js
Download and install the latest LTS version of Node.js from:
👉 https://nodejs.org
Verify installation:
Step 2: Create a React App
The modern way to create a React app is using Vite (faster than Create React App).
Open the shown local URL (usually http://localhost:5173).
✅ 2. Understanding JSX
React uses JSX (JavaScript XML) — a syntax extension that looks like HTML but is written inside JavaScript.
Example:
JSX Rules:
Must return a single parent element
Use
classNameinstead ofclassJavaScript expressions go inside
{ }
Example:
✅ 3. Create Functional Components
In React, components are reusable UI blocks.
Example: Functional Component
Inside App.jsx:
✅ 4. Render Components to the DOM
React renders components using createRoot.
Inside main.jsx:
📌 Expected Output
When you open the browser:
🎯 Learning Outcomes
After completing this lab, you should be able to:
Install and configure React environment
Understand JSX syntax
Create functional components
Render components into the browser DOM
LAB 2
🔹 Lab Program 2: React Components, Props & State
🎯 Aim
Implement component-based architecture in React.
✅ Task 1: Create Reusable Components
📁 Project Structure
🔹 Header Component (Header.jsx)
🔹 UserCard Component (UserCard.jsx)
✅ Task 2: Pass Data Using Props
Props allow data to be passed from parent to child.
🔹 Use Components in App.jsx
📌 Here:
-
nameandageare passed as props. -
Components become reusable with different data.
✅ Task 3: Manage State Using useState
React state allows components to store and update data dynamically.
🔹 Counter Component (Counter.jsx)
🔹 Add Counter in App.jsx
✅ Task 4: Conditional Rendering
Render UI based on conditions.
🔹 Example: Show Message Based on Count
Modify Counter.jsx:
OR using &&:
📌 Expected Output
-
Header displayed
-
Multiple reusable UserCards
-
Counter with increment/decrement
-
Message changes based on count value
🎯 Learning Outcomes
After completing this lab, you can:
-
Create reusable React components
-
Pass and receive props
-
Manage dynamic data using
useState -
Implement conditional rendering
LAB 3
🔹 Lab Program 3: React Hooks, Forms & Routing
🎯 Aim
Build a multi-page application using React with hooks, forms, and routing.
✅ Task 1: Form Handling in React
📁 Project Structure
🔹 Contact Form Example (Contact.jsx)
✅ Task 2: useEffect and useRef Hooks
🔹 useEffect
-
Used for side effects (API calls, DOM updates, timers)
-
Runs after component renders
Example:
🔹 useRef
-
Access DOM elements
-
Store mutable values without re-rendering
Example:
✅ Task 3: Client-Side Routing
Install React Router
🔹 Setup Routing (App.jsx)
🔹 Simple Page Components
Home.jsx
About.jsx
✅ Task 4: Navigation Between Pages
-
<Link>prevents full page reload -
URL changes without refreshing
-
Navigation is smooth and fast
Example:
📌 Expected Output
-
Multi-page navigation (Home, About, Contact)
-
Working contact form
-
Auto-focus using
useRef -
Console log using
useEffect -
No page reload while switching pages
🎯 Learning Outcomes
After completing this lab, you can:
-
Handle forms in React
-
Use
useState,useEffect,useRef -
Implement client-side routing
-
Navigate between multiple pages
LAB 4
🔹 Lab Program 4: Node.js & Express Server Setup
🎯 Aim
Create a backend server using Node.js and Express.js.
✅ Step 1: Project Setup
1️⃣ Initialize Project
2️⃣ Install Express
✅ Step 2: Setup Express Server
Create a file: server.js
▶ Run Server
Open:
👉 http://localhost:5000
✅ Step 3: Create Routes
Routes define API endpoints.
Add below routes in server.js:
✅ Step 4: Use Middleware
Middleware runs before request reaches the route.
🔹 Custom Middleware Example
Now every request logs method and URL.
✅ Step 5: Send JSON Responses
Use:
Example:
📌 Expected Output
Server runs on port 5000
/→ Displays message/api/users→ Returns JSON list/api/status→ Returns JSON responseLogs every request in console
🎯 Learning Outcomes
After completing this lab, you can:
Initialize a Node project
Setup Express server
Create GET & POST routes
Use middleware
Send JSON responses
LAB 5
🔹 Lab Program 5: RESTful API with CRUD Operations
🎯 Aim
Design and implement a REST API using Node.js and Express.js.
✅ Step 1: Project Setup
Create server.js
✅ Step 2: Setup Express Server
✅ Step 3: Create REST Endpoints (CRUD)
We’ll simulate a database using an array.
🔹 1️⃣ GET – Retrieve All Users
🔹 2️⃣ GET – Retrieve Single User
🔹 3️⃣ POST – Create New User
🔹 4️⃣ PUT – Update User
🔹 5️⃣ DELETE – Remove User
✅ Step 4: Error Handling in Express
🔹 Global Error Handler Middleware
Example usage:
✅ Step 5: Testing with Postman
Use Postman to test endpoints.
🔹 Example Requests:
| Method | URL | Body (JSON) |
|---|---|---|
| GET | http://localhost:5000/api/users | — |
| GET | http://localhost:5000/api/users/1 | — |
| POST | http://localhost:5000/api/users | { "name": "Rahul", "age": 23 } |
| PUT | http://localhost:5000/api/users/1 | { "name": "Updated Name" } |
| DELETE | http://localhost:5000/api/users/1 | — |
Set Body → Raw → JSON in Postman.
📌 Expected Output
API supports full CRUD
Proper status codes (200, 201, 400, 404, 500)
JSON responses
Errors handled properly
🎯 Learning Outcomes
After completing this lab, you can:
Design RESTful endpoints
Handle JSON requests and responses
Implement CRUD operations
Implement error handling
Test APIs using Postman
LAB 6
🔹 Lab Program 6: MongoDB Integration with Node.js
🎯 Aim
Connect MongoDB with an Express.js backend using Mongoose.
✅ Step 1: Install MongoDB & Dependencies
1️⃣ Install MongoDB
Download and install MongoDB Community Server from:
👉 https://www.mongodb.com/try/download/community
Start MongoDB service.
2️⃣ Install Required Packages
Inside your project folder:
✅ Step 2: Connect MongoDB with Node.js
Create server.js:
✅ Step 3: Create Schema & Model
Create folder: models/User.js
✅ Step 4: Perform CRUD Operations
Update server.js:
✅ Step 5: Input Validation
Validation is handled via Mongoose schema:
If invalid data is sent:
Required fields missing → 400 error
Age < 18 → Validation error
Duplicate email → Error
✅ Step 6: Test Using Postman
Use Postman:
🔹 Example POST Request
Body (JSON):
📌 Expected Output
MongoDB connected successfully
Data stored in
lab6dbFull CRUD working
Schema validation enforced
Proper error responses
🎯 Learning Outcomes
After completing this lab, you can:
Connect MongoDB with Express
Create schemas & models
Perform database CRUD operations
Implement validation using Mongoose
Handle async/await operations
LAB 7
🎯 Aim
Implement data relationships and aggregation using MongoDB with Mongoose in a Node.js + Express.js backend.
✅ 1️⃣ Reference & Embedded Documents
MongoDB supports two types of relationships:
🔹 A) Embedded Documents (One-to-Few)
Example: A user with multiple addresses embedded.
📁 models/User.js
Example Data:
✔ Best for small, tightly related data
✔ Faster reads
🔹 B) Referenced Documents (One-to-Many)
Example: One user → Many posts
📁 models/Post.js
✔ Better for large datasets
✔ Avoids duplication
✅ 2️⃣ Populate Related Data
populate() replaces ObjectId with actual document data.
Example Route
Output:
✅ 3️⃣ Basic Aggregation Queries
Aggregation is used for data analysis.
🔹 Count Users by City
🔹 Average Age of Users
✅ 4️⃣ Optimize Database Queries
🔹 A) Use Indexes
Add index in schema:
Or manually:
✔ Improves search speed
✔ Required for large datasets
🔹 B) Select Only Required Fields
✔ Reduces data transfer
✔ Faster response
🔹 C) Pagination
✔ Prevents large data loading
📌 Expected Output
-
Embedded documents working
-
Referenced documents working
-
populate()fetching related data -
Aggregation queries returning grouped results
-
Indexed & optimized queries
🎯 Learning Outcomes
After completing this lab, you can:
-
Design relationships in MongoDB
-
Use embedded & referenced documents
-
Fetch related data using
populate() -
Perform aggregation queries
-
Optimize MongoDB performance
LAB 8
🔹 Lab Program 8: React + Backend Integration
🎯 Aim
Connect a React frontend with a Express.js backend API.
✅ Prerequisites
Make sure:
-
Backend server is running (e.g.,
http://localhost:5000) -
React app is running (e.g.,
http://localhost:5173) -
CORS is enabled in backend:
✅ 1️⃣ Fetch Data using Axios / Fetch API
Install Axios (optional):
🔹 Example Backend API (Express)
🔹 Fetch Data in React (Using Axios)
📁 Users.jsx
✅ 2️⃣ Display Backend Data in React
Import in App.jsx:
✅ 3️⃣ Handle Loading & Error States
We handled:
-
loading→ Shows "Loading..." -
error→ Shows error message -
Success → Displays user list
This improves user experience and robustness.
✅ 4️⃣ Environment Variables Usage
Create .env file in React root:
⚠ Restart development server after adding .env.
Access inside React:
📌 Expected Output
-
React fetches data from backend
-
Data displayed dynamically
-
Loading message shown initially
-
Error message displayed if request fails
-
API URL managed via environment variable
🎯 Learning Outcomes
After completing this lab, you can:
-
Connect React frontend with backend API
-
Use Axios / Fetch API for HTTP requests
-
Manage loading & error states
-
Use environment variables securely
-
Understand frontend-backend communication flow
LAB 9
🔹 Lab Program 9: Authentication with JWT
🎯 Aim
Implement secure authentication and authorization using Node.js, Express.js, MongoDB, and React.
✅ Step 1: Install Required Packages
Backend Dependencies
-
bcryptjs → Password hashing
-
jsonwebtoken → Token generation
-
dotenv → Environment variables
✅ Step 2: User Model with Password Hashing
📁 models/User.js
✅ Step 3: User Registration
📁 routes/auth.js
✅ Step 4: User Login & JWT Token Generation
✅ Step 5: Environment Variables
Create .env file:
In server.js:
✅ Step 6: Middleware for Authorization
📁 middleware/auth.js
✅ Step 7: Protected Route Example
Now only users with valid JWT can access this route.
✅ Step 8: Protected Routes in React
Store token after login:
🔹 Axios with Authorization Header
🔹 React Protected Route Example
Usage:
📌 Expected Output
-
Users can register
-
Passwords stored securely (hashed)
-
Login returns JWT token
-
Protected routes require valid token
-
Unauthorized users cannot access protected data
🎯 Learning Outcomes
After completing this lab, you can:
-
Implement authentication with JWT
-
Hash passwords securely
-
Create login & registration APIs
-
Protect backend routes with middleware
-
Protect frontend routes in React
-
Understand authentication vs authorization
LAB 10
🔹 Lab Program 10: Full-Stack MERN Project & Deployment
🎯 Aim
Develop and deploy a complete MERN stack application using:
-
MongoDB
-
Express.js
-
React
-
Node.js
✅ Project Options (Choose One)
1️⃣ E-commerce App
-
User authentication
-
Product listing
-
Cart & checkout
-
Admin product management
2️⃣ Chat Application
-
User login
-
Real-time messaging
-
Online users
-
Message history
3️⃣ Task Management System (Recommended for Lab)
-
User authentication
-
Create / update / delete tasks
-
Task status tracking
-
Dashboard view
🏗 Suggested Project: Task Management System
✅ 1️⃣ Project Architecture
✅ 2️⃣ Backend Features
📌 APIs Required
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/auth/register | Register user |
| POST | /api/auth/login | Login user |
| GET | /api/tasks | Get user tasks |
| POST | /api/tasks | Create task |
| PUT | /api/tasks/:id | Update task |
| DELETE | /api/tasks/:id | Delete task |
📌 Task Schema Example
✅ 3️⃣ Frontend Integration
Install Axios
Fetch Tasks Example
✅ 4️⃣ State Management
🔹 Option A: Context API (Simple Projects)
Create AuthContext.js:
Wrap in main.jsx.
🔹 Option B: Redux (Large Projects)
Use Redux for complex state handling.
✅ 5️⃣ Optional: Real-Time Features
Install Socket.io
Backend:
Frontend:
Example use cases:
-
Real-time task updates
-
Live chat messages
-
Notifications
✅ 6️⃣ Deployment
🔹 Backend Deployment
Deploy on:
-
Render
-
Railway
Steps:
-
Push code to GitHub
-
Connect GitHub repo to Render/Railway
-
Add environment variables (MongoDB URI, JWT secret)
-
Deploy
🔹 Frontend Deployment
Deploy on:
-
Vercel
-
Netlify
Steps:
-
Push frontend to GitHub
-
Import project
-
Add environment variable:
-
Deploy
✅ 7️⃣ Project Documentation
Include:
📄 README.md
-
Project title
-
Tech stack
-
Installation steps
-
API endpoints
-
Environment variables
-
Deployment links
📄 Screenshots
-
Login page
-
Dashboard
-
CRUD operations
-
Deployment proof
📌 Evaluation Checklist
✔ Frontend + backend fully integrated
✔ JWT authentication working
✔ CRUD operations implemented
✔ Proper error handling
✔ Environment variables configured
✔ Deployed successfully
✔ Clean folder structure
✔ README documentation
🎯 Learning Outcomes
After completing this lab, you can:
-
Build a complete MERN stack application
-
Integrate frontend & backend securely
-
Manage global state
-
Implement authentication
-
Deploy full-stack applications
-
Document and present projects professionally
UNIT 1
🌐 Overview of Web Development
Web development is generally divided into Frontend, Backend, and Full-Stack development. Each plays a different role in building web applications.
1️⃣ Frontend Development (Client-Side)
Frontend is everything users see and interact with in their browser.
🔹 Responsibilities:
-
Designing layouts
-
Styling pages
-
Creating interactive elements
-
Handling user input
-
Communicating with backend APIs
Designing layouts
Styling pages
Creating interactive elements
Handling user input
Communicating with backend APIs
🔹 Technologies:
-
HTML – Structure
-
CSS – Styling
-
JavaScript – Interactivity
-
Frameworks/Libraries:
-
React
-
Angular
-
Vue.js
HTML – Structure
CSS – Styling
JavaScript – Interactivity
Frameworks/Libraries:
-
React
-
Angular
-
Vue.js
🔹 Example:
When you click a button on a website and a form appears without reloading the page — that’s frontend logic working.
2️⃣ Backend Development (Server-Side)
Backend works behind the scenes. It handles logic, database operations, authentication, and server communication.
🔹 Responsibilities:
-
Managing databases
-
Handling user authentication
-
Processing business logic
-
Creating APIs
-
Ensuring security
Managing databases
Handling user authentication
Processing business logic
Creating APIs
Ensuring security
🔹 Technologies:
-
Programming languages:
-
Node.js
-
Python
-
Java
-
PHP
-
Databases:
-
MySQL
-
MongoDB
-
PostgreSQL
Programming languages:
-
Node.js
-
Python
-
Java
-
PHP
Databases:
-
MySQL
-
MongoDB
-
PostgreSQL
🔹 Example:
When you log in to a website and your credentials are verified using a database — that’s backend processing.
3️⃣ Full-Stack Development
A Full-Stack Developer works on both frontend and backend.
They:
-
Build UI
-
Create APIs
-
Connect frontend to backend
-
Manage databases
-
Deploy applications
Popular Full-Stack Combinations:
-
MERN Stack (MongoDB + Express + React + Node)
-
MEAN Stack (MongoDB + Express + Angular + Node)
-
Django + React
-
Spring Boot + React
MERN Stack (MongoDB + Express + React + Node)
MEAN Stack (MongoDB + Express + Angular + Node)
Django + React
Spring Boot + React
Since you’re already working with React and backend systems, full-stack development would be a natural fit for you.
💻 HTML, CSS, JavaScript Fundamentals
These are the three core building blocks of the web.
🧱 1. HTML (HyperText Markup Language)
HTML defines the structure of a webpage.
Example:
Key Concepts:
-
Elements (<h1>, <p>, <div>)
-
Attributes (id, class)
-
Forms (<input>, <form>)
-
Semantic tags (<header>, <footer>, <section>)
Elements (<h1>, <p>, <div>)
Attributes (id, class)
Forms (<input>, <form>)
Semantic tags (<header>, <footer>, <section>)
Think of HTML as the skeleton of a website.
🎨 2. CSS (Cascading Style Sheets)
CSS controls the appearance of a webpage.
Example:
Key Concepts:
-
Selectors (.class, #id)
-
Box model (margin, padding, border)
-
Flexbox
-
Grid
-
Responsive design (media queries)
Selectors (.class, #id)
Box model (margin, padding, border)
Flexbox
Grid
Responsive design (media queries)
CSS is the design and styling layer.
⚡ 3. JavaScript (JS)
JavaScript makes webpages interactive and dynamic.
Example:
Key Concepts:
-
Variables (let, const)
-
Functions
-
DOM Manipulation
-
Events
-
Fetching data from APIs
-
Async/Await
Variables (let, const)
Functions
DOM Manipulation
Events
Fetching data from APIs
Async/Await
JavaScript is the brain of the frontend.
🔄 How They Work Together
Layer Technology Purpose Structure HTML Builds content Styling CSS Makes it look good Logic JavaScript Makes it interactive Data & Security Backend Handles data & logic
| Layer | Technology | Purpose |
|---|---|---|
| Structure | HTML | Builds content |
| Styling | CSS | Makes it look good |
| Logic | JavaScript | Makes it interactive |
| Data & Security | Backend | Handles data & logic |
🚀 Simple Real-World Flow
Example: User logs into a website
-
HTML → Displays login form
-
CSS → Styles the form
-
JavaScript → Captures user input
-
Backend → Verifies credentials
-
Database → Stores/retrieves user data
⚛ Introduction to React.js
🔹 What is React?
React is a JavaScript library used to build interactive user interfaces, especially for single-page applications (SPAs).
It was developed by Meta.
🔹 Why React?
-
Component-based architecture
-
Reusable UI blocks
-
Fast rendering using Virtual DOM
-
Large ecosystem
-
Strong community support
🔹 How React Works
Instead of manipulating the DOM directly:
-
React creates a Virtual DOM
-
Compares changes
-
Updates only what is necessary
This makes React fast and efficient.
🧱 Components, JSX, Props, State
🔹 1. Components
Components are reusable building blocks of a React app.
Two types:
-
Functional Components (modern & recommended)
-
Class Components (older approach)
Example (Functional Component):
Use it like:
🔹 2. JSX
JSX = JavaScript XML
It allows you to write HTML inside JavaScript.
Example:
Behind the scenes, JSX gets converted to:
Rules:
-
Must return a single parent element
-
Use
classNameinstead ofclass -
JavaScript inside
{}
Example:
🔹 3. Props
Props (short for properties) allow passing data from parent to child component.
Example:
Usage:
You can also destructure:
Props are read-only.
🔹 4. State
State allows a component to store and manage dynamic data.
In modern React, we use useState.
Example:
-
count→ current state -
setCount→ function to update state
When state updates → component re-renders.
🔄 Functional vs Class Components
🔹 Functional Components (Recommended)
With Hooks:
Advantages:
-
Cleaner syntax
-
Less code
-
Hooks support lifecycle
-
Industry standard today
🔹 Class Components (Older)
Used lifecycle methods like:
-
componentDidMount()
-
componentDidUpdate()
-
componentWillUnmount()
Today, Hooks replace lifecycle methods.
🖱 Event Handling & Forms
🔹 Event Handling in React
React events are written in camelCase.
Example:
Common Events:
-
onClick
-
onChange
-
onSubmit
-
onMouseEnter
🔹 Forms in React
React uses controlled components for forms.
Controlled = Form data is controlled by state.
Example: Input Field
Example: Form Submission
🎯 Key Concepts You Must Master
✔ Components
✔ JSX
✔ Props
✔ State
✔ Event handling
✔ Controlled forms
✔ Functional components + Hooks
⚛ React Hooks
Hooks let you use state and lifecycle features in functional components in React.
🪝 1️⃣ useState
useState is used to manage component state.
🔹 Syntax
🔹 Example: Counter
When setCount runs → component re-renders.
🪝 2️⃣ useEffect
useEffect handles side effects like:
-
API calls
-
Timers
-
Event listeners
-
Component lifecycle behavior
🔹 Syntax
🔹 Run Only Once (Component Mount)
Empty dependency array → runs once.
🔹 Run When State Changes
🔹 Cleanup Example
Cleanup runs when component unmounts.
🪝 3️⃣ useRef
useRef is used to:
-
Access DOM elements
-
Store values without causing re-render
🔹 Access Input Field
🔹 Store Mutable Value
Unlike state, updating useRef does NOT trigger re-render.
🛣 Routing with React Router
We use React Router to navigate between pages in a React app.
🔹 Install
🔹 Basic Setup
🔹 Navigation Links
🔹 Dynamic Route Example
Access param:
🚀 Basic Project: Simple React Website
Let’s build a 3-page portfolio website.
📁 Project Structure
🧱 Step 1: Navbar Component
🏠 Step 2: Home Page
📄 Step 3: About Page
📬 Step 4: Contact Page (Form + useState)
🧩 Step 5: App.js
🎯 What You Just Learned
✔ useState → manage state
✔ useEffect → lifecycle & side effects
✔ useRef → DOM access
✔ React Router → multi-page navigation
✔ Built a small real project
🟢 1️⃣ Introduction to Node.js
🔹 What is Node.js?
Node.js is a JavaScript runtime that allows you to run JavaScript outside the browser, mainly on the server.
It is built on Chrome’s V8 engine.
Before Node:
-
JavaScript only ran in browsers.
After Node:
-
JavaScript can power full backend servers.
🔹 Why Node.js?
-
Fast execution (V8 engine)
-
Non-blocking I/O
-
Event-driven architecture
-
Highly scalable
-
Same language (JS) for frontend & backend
🧠 Node.js Architecture
Node.js uses:
1️⃣ Single-Threaded Model
It runs on one main thread.
2️⃣ Event Loop
Handles asynchronous operations efficiently.
Instead of blocking code, Node:
-
Receives request
-
Delegates heavy tasks (file/db/network)
-
Registers callback
-
Continues handling other requests
-
Executes callback when task completes
This is called Non-Blocking I/O.
🔹 Blocking vs Non-Blocking Example
Blocking (Bad for performance)
Non-Blocking (Preferred)
Node is powerful because it doesn’t wait for one request to finish before handling another.
🚀 2️⃣ Setting Up Express.js Server
🔹 What is Express?
Express.js is a lightweight web framework for Node.js used to build APIs and web servers easily.
🔹 Step 1: Initialize Project
🔹 Step 2: Install Express
🔹 Step 3: Create Basic Server
Create server.js:
Run server:
Open:
🛣 3️⃣ Routing in Express
Routing determines how your server responds to requests.
Basic syntax:
🔹 Example Routes
🔹 Route Parameters
🔹 Query Parameters
🔄 4️⃣ Middleware in Express
Middleware functions execute between request and response.
Structure:
🔹 Basic Middleware Example
If you don’t call next(), request will hang.
🔹 Built-in Middleware
🔹 Router-Level Middleware
🔹 Middleware Example: Authentication
🏗 Recommended Backend Structure (For MERN)
🎯 What You Should Practice Now
Since you're building full-stack systems:
-
Build a CRUD API
-
Connect MongoDB
-
Add JSON parsing
-
Implement error handling middleware
-
Add JWT authentication
-
Test with Postman
🌐 1️⃣ RESTful API Design
🔹 What is REST?
REST = Representational State Transfer
It is an architectural style for designing web APIs using HTTP methods properly.
🔹 Core Principles of REST
-
Client–Server separation
-
Stateless communication
-
Use HTTP methods correctly
-
Resource-based URLs
🔹 HTTP Methods in REST
| Method | Purpose |
|---|---|
| GET | Retrieve data |
| POST | Create data |
| PUT | Update entire resource |
| PATCH | Update partial resource |
| DELETE | Remove data |
🔹 Good RESTful URL Design
✅ Good:
❌ Bad:
Use nouns, not verbs.
🔹 Example: User API
📦 2️⃣ Handling JSON Requests & Responses
By default, Express does NOT parse JSON unless you enable middleware.
🔹 Enable JSON Parsing
This allows you to access:
🔹 Handling JSON Request
Client sends:
Server:
🔹 Sending JSON Response
Always use:
Example:
🔹 Status Codes You Must Know
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Server Error |
Good APIs use correct status codes.
⚠ 3️⃣ Error Handling in Express
Errors should NOT crash your server.
🔹 Basic Error Example
This can crash server if not handled properly.
🔹 Centralized Error Middleware (Best Practice)
Must have 4 parameters:
Place this after all routes.
🔹 Async Error Handling
Use next(error) to forward error.
🔹 Custom Error Class (Professional Approach)
Then:
🔐 4️⃣ Environment Variables & Configuration (dotenv)
Hardcoding secrets ❌
Using environment variables ✅
🔹 Install dotenv
🔹 Create .env File
🔹 Load dotenv (VERY IMPORTANT: at top of file)
🔹 Use Environment Variables
🔹 Why dotenv is Important?
-
Keeps secrets secure
-
Different config for dev/prod
-
Cleaner codebase
-
Safer deployments
🏗 Recommended Production Structure
🎯 What You Should Practice Next
Since you're building serious full-stack systems:
-
Build a CRUD REST API
-
Add centralized error handler
-
Use dotenv properly
-
Add validation (Joi / express-validator)
-
Implement JWT authentication
-
Connect to MongoDB
UNIT 3
🟢 1️⃣ Introduction to NoSQL and MongoDB
🔹 What is NoSQL?
NoSQL = Non-relational database
Unlike SQL databases (MySQL, PostgreSQL):
No fixed schema
Stores data in flexible formats
Highly scalable
Better for unstructured data
🔹 Types of NoSQL Databases
Document-based → MongoDB
Key-value → Redis
Column-based → Cassandra
Graph → Neo4j
🍃 What is MongoDB?
MongoDB is a document-based NoSQL database.
Instead of tables and rows, it uses:
Database
Collections
Documents (JSON-like objects)
🔹 Example MongoDB Document
Documents are stored in BSON (Binary JSON).
⚙ 2️⃣ Installing and Connecting MongoDB with Node.js
There are 2 common ways:
MongoDB Native Driver
Mongoose (Recommended for beginners & MERN)
We’ll use Mongoose.
🔹 Step 1: Install MongoDB
Download from:
👉 https://www.mongodb.com/
Or use:
MongoDB Atlas (Cloud)
🔹 Step 2: Install Dependencies
Inside your backend folder:
🔹 Step 3: Connect MongoDB to Node.js
Create config/db.js
Use in server.js
🏗 3️⃣ Creating a Schema & Model
MongoDB is schema-less, but Mongoose allows structure.
Create models/User.js
🔄 4️⃣ CRUD Operations Using MongoDB
CRUD = Create, Read, Update, Delete
🟢 CREATE
🔵 READ (All Users)
🔵 READ (Single User)
🟡 UPDATE
🔴 DELETE
🧠 Best Practices
✔ Use async/await
✔ Wrap in try/catch
✔ Validate input
✔ Use environment variables for DB URI
✔ Separate routes/controllers
🏗 Recommended Project Structure
🎯 What You Should Practice Now
Since you're building serious full-stack systems:
Build full CRUD API
Add validation
Add error handling middleware
Connect React frontend
Implement authentication
Here’s a clear and practical guide to mastering Mongoose and advanced MongoDB concepts for real-world MERN apps 🚀
We’ll cover:
-
✅ Mongoose ODM (Schemas, Models, Validation)
-
✅ Data Relationships in MongoDB
-
✅ Query Optimization & Aggregation Basics
🟢 1️⃣ Mongoose ODM: Schemas, Models & Validation
🔹 What is Mongoose?
Mongoose is an ODM (Object Data Modeling) library for MongoDB used with Node.js.
ODM = Bridge between MongoDB documents and JavaScript objects.
It provides:
-
Schema structure
-
Validation
-
Middleware (hooks)
-
Query building
🧱 Schemas in Mongoose
A Schema defines the structure of documents inside a collection.
🔹 Basic Schema Example
🏗 Models in Mongoose
A Model is a wrapper around a schema.
Now you can:
✅ Validation in Mongoose
Validation ensures clean and safe data.
🔹 Built-in Validators
🔹 Custom Validation
🔹 Handling Validation Errors
🔄 2️⃣ Data Relationships in MongoDB
MongoDB is NoSQL, but relationships are still possible.
Two main approaches:
🟢 1. Embedding (Denormalization)
Store related data inside a document.
Example: Blog with Comments
✔ When to Use:
-
Small related data
-
Data always fetched together
🔵 2. Referencing (Normalization)
Store reference IDs.
Example: User & Post Relationship
🔹 Using populate()
populate() replaces ObjectId with actual user document.
✔ When to Use Referencing:
-
Large data
-
Many-to-many relationships
-
Data queried separately
🔷 Relationship Types
| Type | Example |
|---|---|
| One-to-One | User → Profile |
| One-to-Many | User → Posts |
| Many-to-Many | Students ↔ Courses |
⚡ 3️⃣ Query Optimization Basics
As your database grows, performance matters.
🟢 1. Indexing
Indexes make queries faster.
Common fields to index:
-
email
-
username
-
foreign keys
-
frequently searched fields
⚠ Over-indexing slows writes.
🔵 2. Use Select to Limit Fields
Fetch only needed fields → faster queries.
🔵 3. Pagination
Avoid loading thousands of records.
Better approach for large data:
-
Cursor-based pagination
📊 4️⃣ Aggregation Basics
Aggregation is used for:
-
Analytics
-
Reports
-
Grouping
-
Summaries
MongoDB uses Aggregation Pipeline.
🔹 Basic Aggregation Example
Count users by age:
🔹 Common Aggregation Stages
| Stage | Purpose |
|---|---|
| $match | Filter data |
| $group | Group data |
| $sort | Sort results |
| $project | Select fields |
| $lookup | Join collections |
🔹 Example: Join Users & Posts
🧠 Real-World Optimization Tips
✔ Use indexes wisely
✔ Avoid large document embedding
✔ Use pagination
✔ Select only needed fields
✔ Use aggregation for reports
✔ Monitor slow queries
🏗 Professional Backend Structure
🎯 What You Should Build Next
Since you're building serious full-stack systems:
-
Blog system (Users + Posts + Comments)
-
E-commerce backend (Products + Orders)
-
Authentication + role-based access
-
Analytics dashboard using aggregation
Here’s a complete full-stack guide to connecting React with Express/MongoDB and implementing JWT authentication 🚀
We’ll cover:
1️⃣ Connecting React frontend with Express backend
2️⃣ Axios / Fetch for HTTP requests
3️⃣ JWT-based authentication & authorization
🔗 1️⃣ Connecting React Frontend with Express + MongoDB Backend
Your architecture:
Frontend sends HTTP requests → Backend handles logic → MongoDB stores data → Response sent back.
🟢 Backend Setup Example
Assume backend running on:
Enable JSON + CORS:
🟢 Frontend Setup (React)
Your React app runs on:
Now we fetch data from backend.
🌐 2️⃣ Axios or Fetch API for HTTP Requests
You can use:
-
Native
fetch() -
Or Axios (more popular in production)
🔵 Option 1: Using Fetch API
🔵 Option 2: Using Axios (Recommended)
Install:
Example:
🔥 Best Practice: Create Axios Instance
Now use:
Cleaner and scalable.
🔐 3️⃣ JWT-Based Authentication & Authorization
JWT = JSON Web Token
Used for:
-
Login authentication
-
Protecting routes
-
Role-based access
Library: jsonwebtoken
🟢 Step 1: Install Backend Dependencies
-
bcryptjs → hash passwords
-
jsonwebtoken → generate tokens
🧱 Step 2: User Model (MongoDB)
🔐 Step 3: Register Route
🔐 Step 4: Login Route (Generate JWT)
🛡 Step 5: Auth Middleware (Protect Routes)
🔐 Protected Route Example
🌐 4️⃣ Sending Token from React
After login:
Send token in requests:
🔒 Role-Based Authorization (Admin Example)
🏗 Full Production Flow
-
User registers
-
Password hashed
-
User logs in
-
JWT generated
-
Token stored in frontend
-
Token sent with every request
-
Backend verifies token
-
Access granted/denied
⚠ Production Best Practices
✔ Store JWT_SECRET in .env
✔ Use HTTPS
✔ Add token expiration
✔ Implement refresh tokens
✔ Never store plain passwords
✔ Use centralized error handling
🎯 What You Should Build Now
Since you're building serious systems, try:
-
Full authentication system
-
Role-based access control (Admin/User)
-
Protected React routes
-
Profile dashboard with JWT
-
Logout functionality
Here’s a complete full-stack production guide covering deployment, state management, structure, and real-time updates 🚀
We’ll cover:
1️⃣ Deployment strategies (Heroku, Vercel, Netlify)
2️⃣ State management (Redux vs Context API)
3️⃣ Project structure & best practices
4️⃣ Optional: Real-time updates with Socket.io
🚀 1️⃣ Deployment Strategies
🌍 Frontend Deployment
🔹 1. Vercel (Best for React)
Vercel
✅ Zero config
✅ Automatic GitHub deployments
✅ Fast global CDN
✅ Great for React & Next.js
Steps:
-
Push code to GitHub
-
Import project in Vercel
-
Deploy
Set environment variables in dashboard.
🔹 2. Netlify
Netlify
Great alternative for static React apps.
Build settings:
🌍 Backend Deployment
🔹 3. Heroku (Traditional Option)
Heroku
Good for Node.js backend hosting.
Steps:
-
Add
Procfile -
Use environment variables
-
Deploy via Git
Example Procfile:
🔥 Modern Backend Alternatives
-
Render
-
Railway
-
Fly.io
🗂 Full MERN Deployment Architecture
Use:
-
MongoDB Atlas connection string
-
Environment variables for secrets
🧠 2️⃣ State Management (Redux vs Context API)
When apps grow, passing props becomes messy → Use state management.
🔵 Option 1: Context API (Built-in React)
Part of React
Good for:
-
Small to medium apps
-
Theme, Auth, User state
🔹 Create Context
Use in component:
✔ When to Use Context?
-
Authentication
-
Dark/light mode
-
Global settings
🔴 Option 2: Redux (Large Apps)
Redux
Best for:
-
Complex global state
-
Large enterprise apps
-
Many reducers
Install:
🔹 Basic Redux Example
Wrap app:
🆚 Redux vs Context
| Feature | Context | Redux |
|---|---|---|
| Complexity | Simple | Advanced |
| Boilerplate | Low | Medium |
| Performance | Medium | High |
| Large apps | ❌ | ✅ |
👉 For most MERN apps:
Start with Context → Move to Redux if needed.
🏗 3️⃣ Project Structure & Best Practices
🔹 Frontend Structure
🔹 Backend Structure
🔥 Best Practices
✔ Use environment variables
✔ Use centralized error handling
✔ Separate business logic (controllers)
✔ Use async/await
✔ Validate input
✔ Use proper HTTP status codes
✔ Keep frontend and backend separate
✔ Never expose secrets in frontend
⚡ 4️⃣ Optional: Real-Time Updates with Socket.io
For:
-
Chat apps
-
Notifications
-
Live dashboards
-
Online gaming
Library: Socket.IO
🔹 Backend Setup
🔹 Frontend Setup
No comments:
Post a Comment