Express.js / Express.js Basics
Understanding Middleware in Express
Middleware is a fundamental concept in Express.js. In this tutorial, you will learn what middleware is, how it works, and how you can use it in your Express applications.
Section overview
5 resourcesCovers the fundamental concepts of Express.js, including installation, setup, and creating a basic application.
Understanding Middleware in Express
1. Introduction
In this tutorial, we will be exploring the concept of middleware in Express.js, a popular and robust web application framework for Node.js. By the end of this tutorial, you will have a solid understanding of what middleware is, how it works, and how to effectively use it in your Express applications.
Prerequisites: Basic knowledge of JavaScript, Node.js and Express.js will be beneficial.
2. Step-by-Step Guide
Middleware are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function in the stack.
Here is a basic example:
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
In this example, the middleware logs the current time, and then passes control to the next middleware function using the next() function.
Best practices and tips:
- Always call
next()unless your middleware is meant to terminate the request-response cycle. If you don't, the request will hang and not proceed to the next middleware or route handler. - Middleware is executed in the order it is added with
app.use(). Be mindful of the order in which you add middleware to your application.
3. Code Examples
Here are some more examples of middleware in action:
Example 1: Middleware function that logs the URL and the date of each request.
app.use(function (req, res, next) {
console.log('Request URL:', req.originalUrl)
console.log('Time:', Date.now())
next()
})
In this example, req.originalUrl contains the original URL path of the request and Date.now() gives the current time in milliseconds since 1970.
Example 2: Middleware function that authenticates a user
app.use(function (req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect('/login')
})
In this example, if the user is authenticated, the middleware calls next(), allowing the request to proceed to the next middleware or route handler. If the user is not authenticated, the middleware sends a response to redirect the user to the login page.
Expected Output: These middleware functions don't have an output that can be directly seen, but you can observe their effects (logging to the console, redirecting the user) when you make requests to your Express app.
4. Summary
In this tutorial, we have learned about middleware in Express.js. We learned that middleware are functions that have access to the request and response objects, and can execute any code, modify the request and response, end the request-response cycle, or pass control to the next middleware function.
Your next steps might include learning about built-in middleware in Express, like express.static, or third-party middleware like body-parser and cors.
Some additional resources include the Express.js documentation on middleware.
5. Practice Exercises
- Create a middleware function that logs the method of each request (GET, POST, etc.).
- Create a middleware function that sends a custom error response if a request is made to a non-existing route.
Solutions:
- Here's a middleware that logs the method of each request:
app.use(function (req, res, next) {
console.log('Request Method:', req.method)
next()
})
- Here's a middleware that sends a custom error response for non-existing routes:
app.use(function (req, res, next) {
res.status(404).send('Sorry, that route does not exist.')
})
Note that this middleware does not call next(), because it's meant to end the request-response cycle when a non-existing route is requested.
For further practice, try building your own Express app and experiment with adding different middleware functions.
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.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest 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