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

Application-Level Middleware in Express.js

Application-level middleware is registered on an Express.js application using methods such as app.use() and app.METHOD().

It allows developers to execute common logic before a request reaches its route handler. For example, we can log incoming requests, check user authentication, validate request data, and add useful information to the request object.

In this tutorial, we will learn how to create application-level middleware, apply it to all routes or selected paths, and control request processing using next().

1. What Is Application-Level Middleware?

Application-level middleware is middleware registered directly on an Express application instance, usually stored in a variable named app.

It can run for every request or only for requests matching a particular path, depending on how it is registered.

JavaScript
const express = require('express');

const app = express();

app.use((req, res, next) => {
    console.log('Application middleware executed');
    next();
});

Here, app.use() registers middleware on the application. The middleware logs a message and calls next() to pass control to the next middleware or matching route handler.

Remember: Application-level middleware is registered on the Express application, whereas router-level middleware is registered on an Express Router.

2. Syntax of Application-Level Middleware

There are two common ways to register application-level middleware.

A. Using app.use()
JavaScript
app.use((req, res, next) => {
    // Middleware logic
    next();
});

Without a path argument, this middleware can run for requests that reach it, depending on the request method and middleware stack order.

B. Using a Specific Path
JavaScript
app.use('/admin', (req, res, next) => {
    console.log('Admin middleware executed');
    next();
});

This middleware runs for requests whose paths match /admin, including paths such as /admin/dashboard.

3. Application Middleware for All Requests

We can use application-level middleware to log every request that reaches the middleware. This is useful for understanding which routes users are accessing.

Example: Request Logging Middleware

JavaScript
const express = require('express');

const app = express();

app.use((req, res, next) => {
    console.log('Method:', req.method);
    console.log('URL:', req.url);

    next();
});

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

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

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

Run the application:

Terminal
npm install express
node app.js

Open http://localhost:3000 and then http://localhost:3000/about in your browser.

Example terminal output:

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

The middleware logs the HTTP method and URL before the corresponding route handler sends the response.

4. Application Middleware for a Specific Route

Sometimes, middleware should execute only for a particular section of an application. For example, we may want to run a check before allowing access to admin routes.

JavaScript
const express = require('express');

const app = express();

app.use('/admin', (req, res, next) => {
    console.log('Admin section accessed');
    next();
});

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

app.get('/admin/dashboard', (req, res) => {
    res.send('Admin Dashboard');
});

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

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

Try these URLs:

URL Middleware Runs? Response
/ No Public Home Page
/admin Yes Admin Home Page
/admin/dashboard Yes Admin Dashboard
Important: This example only demonstrates path-specific middleware. Logging access to an admin path does not authenticate the user or protect the route. Real applications must implement proper authentication and authorization checks.

5. Middleware Using app.get()

Application-level middleware can also be registered using HTTP method-specific methods. For example, a callback registered with app.get() can execute as part of handling matching GET requests.

JavaScript
const express = require('express');

const app = express();

app.get(
    '/profile',
    (req, res, next) => {
        console.log('Profile middleware executed');
        next();
    },
    (req, res) => {
        res.send('User Profile Page');
    }
);

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

Here, the first callback acts as middleware for the GET /profile request. It calls next(), allowing the second callback to send the response.

Browser URL:

http://localhost:3000/profile

Browser output:

User Profile Page

6. How Application-Level Middleware Works

Express processes middleware and route callbacks in their registered order. Calling next() passes control forward through the middleware stack.

Client Request

Browser requests a URL

↓
Application Middleware

Logs, checks, or processes the request

↓
next()

Passes control to the next handler

↓
Route Handler

Processes the requested route

↓
Response

Sends the result to the client

Middleware may also send a response directly or pass an error using next(err). In those cases, the normal flow can change.

7. Difference Between Global and Path-Specific Middleware

Global Application Middleware Path-Specific Middleware
Registered without a path. Registered with a path such as /admin.
Can run for all matching requests reaching it. Runs only for requests matching the specified path.
Useful for request logging and common processing. Useful for processing a specific section of an application.
app.use(middleware) app.use('/admin', middleware)

Important Points to Remember

  • Application-level middleware is registered on the Express application.
  • app.use() registers middleware with an optional path.
  • Middleware without a path can run for all requests that reach it.
  • Path-specific middleware runs for matching paths.
  • app.get() can register callbacks for GET requests.
  • Middleware registration order matters.
  • Call next() to continue processing when appropriate.
  • Logging is not a replacement for authentication or authorization.

Summary

Application-level middleware is registered directly on an Express.js application. It can execute for all requests reaching it or only for requests matching a specified path.

By using app.use() and method-specific registration such as app.get(), developers can organize common request-processing logic and control how requests move through the application.