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.
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.
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:
- The client sends an HTTP request.
- Express executes the registered custom middleware.
- The middleware performs its task, such as logging or validation.
- When appropriate, the middleware calls
next(). - The matching route handler processes the request.
- The server sends a response to the client.
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
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
npm init -y
npm install express
Step 3: Run the application
node app.js
Step 4: Open these URLs
http://localhost:3000http://localhost:3000/about
Example terminal 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.
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.
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:
{
"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.
{
"message": "Access granted",
"data": [
"JavaScript",
"Node.js",
"Express.js"
]
}
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()
Invalid Request
Send an 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.
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:
{
"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, andnext. - 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.