Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Middleware Introduction in Express.js

Middleware is one of the most important concepts in Express.js. It allows us to execute code during the request-response cycle.

Whenever a client sends a request to an Express.js server, middleware functions can execute before the final response is sent back to the client.

Middleware can perform different tasks, such as logging requests, checking authentication, processing request data, and handling errors. It helps us organize application logic into reusable functions.

1. What Is Middleware?

Middleware is a function that executes during the request-response cycle of an Express.js application.

A middleware function generally receives three parameters:

  • req: Contains information about the incoming request.
  • res: Used to send a response to the client.
  • next: A function that passes control to the next middleware.
JavaScript
function myMiddleware(req, res, next) {
    console.log("Middleware executed");

    next();
}

In this example, the middleware prints a message and calls next() to continue processing the request.

Remember: If middleware neither sends a response nor calls next(), the request may remain pending.

2. Why Do We Need Middleware?

Middleware helps us perform common operations before a request reaches its final route handler.

Purpose Description
Logging Records details about incoming requests.
Authentication Checks whether a user is authenticated.
Request Parsing Reads JSON or form data from requests.
Validation Checks whether incoming data is valid.
Error Handling Handles errors that occur in the application.
Static Files Serves files such as CSS, JavaScript, and images.

3. How Middleware Works

Express.js processes middleware according to the order in which it is registered. A middleware can pass control to the next function or finish the request by sending a response.

Client Request

Browser or API client sends a request

↓
Middleware 1

Logs request information

↓
Middleware 2

Checks or processes request data

↓
Route Handler

Processes the requested URL

↓
Server Response

Response is sent to the client

Important: The diagram shows a typical flow. Middleware can also send a response directly, stop further processing, or pass errors to error-handling middleware.

4. Creating Your First Middleware

Let us create a simple Express.js application that displays a message in the terminal whenever a request arrives.

Step 1: Install Express.js

Terminal
npm init -y
npm install express

Step 2: Create a file named app.js

JavaScript
const express = require('express');

const app = express();

// Middleware function
app.use((req, res, next) => {
    console.log('A request was received');
    next();
});

// Route handler
app.get('/', (req, res) => {
    res.send('Welcome to Express.js Middleware!');
});

// Start server
app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});

Step 3: Run the application

Terminal
node app.js

Step 4: Open the browser

URL: http://localhost:3000

Browser Output:

Welcome to Express.js Middleware!

Terminal Output:

Output
Server running at http://localhost:3000
A request was received

Whenever you open the URL or refresh the page, the middleware logs the request message and calls next(). The route handler then sends the response.

5. Understanding app.use()

The app.use() method registers middleware in an Express.js application. Middleware registered without a path generally runs for every incoming request that reaches it, subject to its position in the middleware stack.

JavaScript
app.use((req, res, next) => {
    console.log(req.method, req.url);
    next();
});

Here, req.method provides the HTTP method, such as GET or POST, while req.url provides the requested URL.

Example terminal output:

Output
GET /
GET /about
GET /products

These lines are examples of what may appear when the corresponding URLs are requested.

6. Types of Middleware in Express.js

Express.js middleware can be grouped according to its purpose and how it is registered.

Type Purpose
Built-in Middleware Provided by Express.js, such as express.json() and express.static().
Application-Level Middleware Registered on the application using methods such as app.use().
Router-Level Middleware Registered on an Express Router using router.use().
Third-Party Middleware Installed from external packages, such as logging middleware.
Error-Handling Middleware Handles errors using four parameters: err, req, res, next.

Important Points to Remember

  • Middleware executes during the request-response cycle.
  • Middleware receives req, res, and next in the usual pattern.
  • Use next() to pass control to the next middleware.
  • Middleware registration order matters.
  • Middleware can modify request or response objects.
  • A middleware can send a response instead of calling next().
  • Error-handling middleware uses four parameters.

Summary

Middleware is a function that runs while an Express.js application processes a request. It is commonly used for logging, authentication, request parsing, validation, and error handling.

The app.use() method registers application middleware, while next() passes control to the next middleware or handler.