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

Custom Middleware in Express.js

Custom middleware is middleware that we create ourselves to perform specific tasks in an Express.js application.

Express.js provides built-in middleware, but sometimes our application needs its own logic. For example, we may want to log incoming requests, check a custom API key, validate data, or measure how long a request takes to process.

In this tutorial, we will learn how to create custom middleware, use the req, res, and next parameters, apply middleware globally and to specific routes, and build practical examples.

1. What Is Custom Middleware?

Custom middleware is a JavaScript function written by a developer to execute logic during the Express.js request-response cycle.

A typical middleware function receives three parameters:

  • req: Contains information about the incoming request.
  • res: Allows us to send a response to the client.
  • next: Passes control to the next middleware or handler.
JavaScript
function myMiddleware(req, res, next) {
    console.log('Custom middleware executed');

    next();
}

In this example, the middleware prints a message in the terminal. It then calls next() so that Express can continue processing the request.

Remember: A middleware function must either continue the request flow appropriately or send a response. If it does neither, the request may remain pending.

2. Why Do We Need Custom Middleware?

Custom middleware helps us write reusable code instead of repeating the same logic inside every route handler.

Purpose Explanation
Request Logging Records the HTTP method and requested URL.
API Key Check Checks whether a request contains a valid API key.
Request Timing Measures the time taken to process a request.
Validation Checks incoming data before a route processes it.
Request Information Adds useful application-specific information to the request.

3. Diagram 1: How Custom Middleware Works

The following diagram shows how a request passes through custom middleware before reaching the route handler.

Client Request

Browser or API client sends a request

↓
Custom Middleware

Executes developer-defined logic

↓
next()

Passes control forward

↓
Route Handler

Processes the request

↓
Server Response

Sends the result to the client

Step-by-step explanation:

  1. The client sends an HTTP request.
  2. Express executes the registered custom middleware.
  3. The middleware performs its task, such as logging or validation.
  4. When appropriate, the middleware calls next().
  5. The matching route handler processes the request.
  6. The server sends a response to the client.
Important: This is the normal flow when next() is called. Middleware can also send a response directly or pass an error using next(err).

4. Creating Your First Custom Middleware

Let us create middleware that displays the HTTP method and URL of each request in the terminal.

Step 1: Create app.js

JavaScript
const express = require('express');

const app = express();

// Custom middleware
function requestLogger(req, res, next) {
    console.log('Method:', req.method);
    console.log('URL:', req.url);

    next();
}

// Register middleware
app.use(requestLogger);

// Route handlers
app.get('/', (req, res) => {
    res.send('Welcome to Home Page');
});

app.get('/about', (req, res) => {
    res.send('Welcome to About Page');
});

// Start server
app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Step 2: Install Express.js

Terminal
npm init -y
npm install express

Step 3: Run the application

Terminal
node app.js

Step 4: Open these URLs

  • http://localhost:3000
  • http://localhost:3000/about

Example terminal output:

Output
Server running on port 3000
Method: GET
URL: /
Method: GET
URL: /about

Whenever you visit one of these URLs, the middleware runs before the route handler and logs the request details.

5. Custom Middleware for a Specific Route

Sometimes we do not want middleware to execute for every request. We can register it only for a particular route.

JavaScript
const express = require('express');

const app = express();

function checkRequest(req, res, next) {
    console.log('Checking profile request');
    next();
}

app.get('/profile', checkRequest, (req, res) => {
    res.send('User Profile Page');
});

app.get('/', (req, res) => {
    res.send('Home Page');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Test the following URLs:

URL Middleware Runs? Response
/ No Home Page
/profile Yes User Profile Page

The checkRequest middleware is passed as a callback to the /profile route. It does not run for the separate home route.

6. Custom Middleware for API Key Validation

We can also create middleware that checks whether a request contains a required API key before allowing the route to continue.

This is a basic demonstration. A real application should load secrets from environment variables or a secure secret store, and should use HTTPS.

JavaScript
const express = require('express');

const app = express();

const API_KEY = process.env.API_KEY || 'demo-key';

function checkApiKey(req, res, next) {
    const apiKey = req.get('x-api-key');

    if (apiKey !== API_KEY) {
        return res.status(401).json({
            message: 'Invalid or missing API key'
        });
    }

    next();
}

app.get('/api/data', checkApiKey, (req, res) => {
    res.json({
        message: 'Access granted',
        data: ['JavaScript', 'Node.js', 'Express.js']
    });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Request without the API key:

JSON Response
{
    "message": "Invalid or missing API key"
}

Request with the correct API key:

Add the header x-api-key with the configured API key. For example, if the application uses the demo fallback value, the header value is demo-key.

JSON Response
{
    "message": "Access granted",
    "data": [
        "JavaScript",
        "Node.js",
        "Express.js"
    ]
}
Security note: The fallback key is for learning only. Do not use a hard-coded demo key in production. Configure a strong secret securely and use proper authentication and authorization for sensitive endpoints.

7. Diagram 2: Custom Middleware Decision Flow

The next diagram shows how middleware can either allow a request to continue or stop it by sending an error response.

Incoming Request

Client calls a protected endpoint

↓
Custom Middleware

Checks request details or API key

↓
Validation Result

Is the request valid?

Valid Request

Call next()

↓
Route Handler
↓
Success Response
Invalid Request

Send an error response

↓
Route Handler Is Skipped
↓
Error Response

Explanation:

  • The middleware receives the incoming request.
  • It checks the required condition, such as whether an API key is valid.
  • If valid, it calls next() to continue processing.
  • If invalid, it sends a response and returns without calling next().
  • This prevents the route handler from running for that rejected request.

8. Adding Custom Data to the Request Object

Custom middleware can add information to the request object so that later middleware or route handlers can use it.

JavaScript
const express = require('express');

const app = express();

app.use((req, res, next) => {
    req.requestTime = new Date().toISOString();
    next();
});

app.get('/', (req, res) => {
    res.json({
        message: 'Request processed',
        requestTime: req.requestTime
    });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Here, the middleware adds a property named requestTime to req. The route handler then reads that property and returns it in the JSON response.

Example response:

JSON
{
    "message": "Request processed",
    "requestTime": "2026-10-16T10:30:00.000Z"
}

The timestamp above is only an example; the application generates the actual timestamp when the request arrives.

9. Common Mistakes in Custom Middleware

Mistake What Happens Correct Approach
Forgetting next() The request may remain pending. Call next() when processing should continue.
Sending a response and then continuing May cause an attempt to send multiple responses. Return after sending the response.
Registering middleware after a route Earlier matching routes may respond before the middleware runs. Register middleware before routes that need it.
Trusting user input without validation May cause incorrect processing or security issues. Validate and sanitize input as appropriate.

Important Points to Remember

  • Custom middleware is written by the developer.
  • It commonly receives req, res, and next.
  • Use app.use() to register application-level middleware.
  • Pass middleware to a route to run it only for that route.
  • Use next() when the request should continue.
  • Send a response when the middleware should finish the request.
  • Use next(err) to pass an error to error-handling middleware.
  • Never rely on a simple API key check as a complete user authentication system.

Summary

Custom middleware allows developers to add application-specific logic to the Express.js request-response cycle. It can be used for logging, request validation, API key checks, timing, and adding useful request information.

By creating reusable middleware functions and registering them in the correct order, we can keep route handlers organized and make our applications easier to maintain.