๐ Introduction
In the previous tutorial, you learned how to create a basic Express.js application.
In this guide, we’ll go deeper into middlewares and routes, which are the core building blocks of every Express application.
By the end of this tutorial, you will clearly understand:
-
How middlewares work in Express
-
How to create custom and route-specific middlewares
-
How to organize routes using Express Router
-
How to handle errors globally
✅ Prerequisites
Before you begin, make sure you have:
-
Node.js and npm installed
-
Basic knowledge of JavaScript
-
A simple Express app (recommended)
๐งฉ Step 1 — Set Up the Project
Create a new project folder:
Initialize the project and install Express:
Create the main file:
๐ง Step 2 — What Is a Middleware?
A middleware is a function that runs between the request and the response.
Middleware can:
-
Log request details
-
Authenticate users
-
Validate data
-
Modify requests or responses
Example: Logger Middleware
Open app.js and add:
Now every incoming request will be logged in the terminal.
๐ฃ️ Step 3 — Add Basic Routes
Test in browser:
⏰ Step 4 — Create Custom Middleware
Create a middleware that checks working hours:
Apply It to a Specific Route
This middleware only runs for the /service route.
๐ Step 5 — Organize Routes with Express Router
Create Routes Folder
Create routes/userRoutes.js
Import Routes into app.js
Test in Browser
๐จ Step 6 — Global Error Handling Middleware
Add this at the bottom of app.js:
This catches unexpected errors safely.
๐ Step 7 — Final app.js File
▶️ Step 8 — Start the Server
Run the server:
Output:
๐งช Test Routes
Open your browser:
๐ง Summary
In this tutorial, you learned how to:
-
Understand and use Express middlewares
-
Create custom and route-specific middlewares
-
Organize routes using Express Router
-
Add global error handling
-
Structure an Express application professionally

