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

Router-Level Middleware in Express.js

Router-level middleware allows us to apply middleware to a specific Express Router instead of registering every middleware directly on the main Express application.

In a large application, we may have different sections such as Users, Products, Admin, and Orders. Each section can have its own routes and middleware. Router-level middleware helps us organize these related routes and apply common logic to them.

Express provides the express.Router() function to create a router. We can register middleware on that router using router.use() or use middleware for a specific route.

1. What Is Router-Level Middleware?

Router-level middleware is middleware registered on an Express Router instance. It works similarly to application-level middleware, but its scope is associated with a particular router.

For example, suppose an application has a separate router for products. We can register middleware on the product router to log requests before they reach the product route handlers.

JavaScript
const express = require('express');

const app = express();
const router = express.Router();

// Router-level middleware
router.use((req, res, next) => {
    console.log('Product router middleware executed');
    next();
});

// Router route
router.get('/list', (req, res) => {
    res.send('Product List');
});

// Mount router on the application
app.use('/products', router);

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

Here, express.Router() creates a separate router. The router.use() method registers middleware on that router, and app.use('/products', router) mounts it under the /products path.

Therefore, when a client requests http://localhost:3000/products/list, the router middleware executes before the matching route handler.

Remember: The route path is /list inside the router, but the complete URL path becomes /products/list after the router is mounted.

2. Why Do We Need Router-Level Middleware?

In a small application, we may write all routes directly inside app.js. But when an application grows, managing every route and its middleware in one file becomes difficult.

Router-level middleware helps us group related routes together and apply common processing logic to that group.

Use Case Explanation
User Routes Apply common checks or logging to user-related routes.
Product Routes Process requests related to products in one router.
Admin Routes Apply authentication and authorization middleware where required.
Order Routes Keep order-related request processing together.
Maintainability Separate route logic into smaller, understandable modules.

3. Diagram 1: How Router-Level Middleware Works

The following diagram shows how a client request moves through the main Express application and into a mounted router.

Client / Browser

Requests /products/list

↓
Express Application (app.js)

Receives the incoming HTTP request

↓
Mounted Router

app.use('/products', productRouter)

↓
Router Middleware

router.use((req, res, next) => ...)

Logs or checks the request

↓
Router Route Handler

router.get('/list', ...)

Processes the matching route

↓
HTTP Response

Sends Product List to the client

Step-by-step explanation:

  1. The client sends a request to /products/list.
  2. The Express application receives the request.
  3. The mounted router matches the /products prefix.
  4. The router middleware runs in registration order.
  5. Calling next() passes control forward.
  6. The matching route handler sends the response.
Important: This is the normal flow for the example. Middleware can also send a response directly, or pass an error to error-handling middleware. In those cases, the route handler may not execute.

4. Creating a Router Using express.Router()

The express.Router() function creates a router object. We can define related routes on this object and mount it in the main application.

Example:

JavaScript
const express = require('express');

const app = express();
const userRouter = express.Router();

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

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

app.use('/users', userRouter);

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

In this example, the router contains two routes. Because the router is mounted at /users, the complete URLs become:

Router Route Complete URL Path Response
/ /users User Home Page
/profile /users/profile User Profile Page

5. Registering Middleware with router.use()

The router.use() method registers middleware on a router. If no path is supplied, the middleware can run for requests handled by that router, according to the order in which middleware and routes are registered.

JavaScript
const express = require('express');

const app = express();
const userRouter = express.Router();

// Middleware for this router
userRouter.use((req, res, next) => {
    console.log('User router middleware executed');
    next();
});

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

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

app.use('/users', userRouter);

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

Test these URLs:

  • http://localhost:3000/users
  • http://localhost:3000/users/profile

Example terminal output:

Output
Server running on port 3000
User router middleware executed
User router middleware executed

Each request reaching the router passes through its middleware before reaching the corresponding route handler. The two log lines represent the two example requests.

6. Diagram 2: Middleware for Multiple Routers

An application can contain multiple routers. Each router can have its own middleware and route handlers, allowing the application to separate different features.

Express Application

app.js

↓
User Router

/users

User Middleware
↓
User Routes
Product Router

/products

Product Middleware
↓
Product Routes

Explanation:

  • The main Express application mounts the user router at /users.
  • The user router can apply middleware to user-related routes.
  • The product router is mounted at /products.
  • The product router can apply different middleware to product-related routes.
  • Each router keeps its related route logic organized separately.
Remember: Router-level middleware is not automatically applied to every router. It runs within the router where it is registered, for requests that reach that middleware.

7. Complete Example with Router-Level Middleware

Let us create a small application that uses a product router and logs requests made to its routes.

Step 1: Create app.js

JavaScript
const express = require('express');

const app = express();
const productRouter = express.Router();

// Router-level middleware
productRouter.use((req, res, next) => {
    console.log(`${req.method} ${req.originalUrl}`);
    next();
});

// Product routes
productRouter.get('/', (req, res) => {
    res.send('All Products');
});

productRouter.get('/:id', (req, res) => {
    res.send(`Product ID: ${req.params.id}`);
});

// Mount the router
app.use('/products', productRouter);

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

Step 2: Install Express and run the application

Terminal
npm init -y
npm install express
node app.js

Step 3: Test the endpoints

Request URL Browser Response Terminal Log
/products All Products GET /products
/products/101 Product ID: 101 GET /products/101

The middleware logs the original request URL. The route /:id captures the product ID through req.params.id.

8. Application-Level vs Router-Level Middleware

Application-Level Router-Level
Registered on the Express application. Registered on an Express Router.
Commonly uses app.use(). Commonly uses router.use().
Can apply common logic across the application. Can apply common logic to a group of related routes.
Example: general request logging. Example: logging requests to product routes.

Important Points to Remember

  • express.Router() creates a router instance.
  • router.use() registers middleware on a router.
  • app.use('/prefix', router) mounts a router at a path.
  • Router middleware executes in registration order.
  • next() passes control to the next handler.
  • Different routers can have different middleware.
  • The mounted path is combined with the route path.
  • Router middleware alone does not provide authentication or authorization.

Summary

Router-level middleware allows us to register middleware on an Express Router instead of applying it directly to the main application.

By using express.Router(), router.use(), and app.use(), we can group related routes, apply common processing logic, and keep larger applications organized and maintainable.