Express.js / Middleware in Express.js
Creating Custom Middleware Functions
In this tutorial, we will learn how to create and use custom middleware functions in Express.js applications.
Section overview
5 resourcesCovers the role of middleware in Express and its different types.
Creating Custom Middleware Functions
Introduction
In this tutorial, we will dive into the world of Express.js to understand and implement custom middleware functions. Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
By the end of this tutorial, you will have a fundamental understanding of how to create and use your own custom middleware in Express.js.
Prerequisites: Basic understanding of JavaScript and Node.js is required. Experience with Express.js can be helpful but not necessary.
Step-by-Step Guide
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
Let's create a simple middleware function that logs the current date and time on each request.
function logDateTime(req, res, next) {
console.log('Time:', Date.now())
next()
}
Here, req is the request object, res is the response object, and next is a callback function that we call to pass control to the next middleware function. If we don't call next(), the request will be left hanging.
We can use this middleware in our application with app.use():
var express = require('express')
var app = express()
app.use(logDateTime)
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Now, every time our app receives a request, it will print the current date and time to the console.
Code Examples
Example 1: A middleware that logs the method and URL of the request.
function logRequestDetails(req, res, next) {
console.log(`Method: ${req.method}, URL: ${req.url}`);
next();
}
app.use(logRequestDetails);
Example 2: A middleware that checks if a user is authenticated.
function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/login');
}
}
app.get('/dashboard', isAuthenticated, function(req, res) {
res.send('Welcome to your dashboard!');
});
In this example, if the user is authenticated, we call next() and continue to the route handler. If they're not authenticated, we redirect them to the login page.
Summary
In this tutorial, we learned how to create and use custom middleware functions in Express.js. We saw that middleware functions can execute any code, make changes to the request and response objects, end the request-response cycle, and call the next middleware in the stack.
Going forward, you can start using custom middleware to handle authentication, logging, error handling, and more in your Express.js applications.
Here are some additional resources to learn more about Express.js middleware:
Practice Exercises
- Create a middleware function that adds a
userobject to the request if a user is logged in. - Create a middleware function that logs the response status code when the response is sent.
- Create a middleware function that checks if a user is an admin before allowing them to access a route.
Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article