This tutorial aims to provide a comprehensive guide on how to implement middleware in Express.js. Middleware is a crucial component in Express.js that allows you to execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack.
By the end of this tutorial, you will:
Before we begin, ensure you have a basic understanding of JavaScript and Node.js. Also, you should have Node.js and Express.js installed on your machine.
Middleware functions 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, denoted as next
.
Middleware functions can:
If the current middleware function does not end the request-response cycle, it must call next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.
Here's how to define an application-level middleware with Express.js.
var express = require('express')
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
In this example, the middleware function is invoked every time the app receives a request. The next()
function is called to pass control to the next middleware function.
Router-level middleware works in the same way as application-level middleware, but it is bound to an instance of express.Router()
.
var express = require('express')
var router = express.Router()
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
Here's a practical example of application-level middleware that prints the current time and request method for each HTTP request.
var express = require('express')
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
console.log('Request Type:', req.method)
next()
})
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
This example demonstrates router-level middleware that logs the request method and URL.
var express = require('express')
var router = express.Router()
router.use(function (req, res, next) {
console.log('Request Type:', req.method)
console.log('Request URL:', req.originalUrl)
next()
})
router.get('/', function (req, res) {
res.send('Hello World!')
})
app.use('/', router)
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
In this tutorial, you learned what middleware is, how it works in Express.js, and how to implement it in your applications. You also worked through practical examples of both application-level and router-level middleware.
To continue learning about Express.js middleware, you can explore error-handling middleware, built-in middleware, and third-party middleware.
Create an Express.js application that uses middleware to log the request method, URL, and current time for every HTTP request.
Create an Express.js application that uses middleware to modify the request object, adding a new property req.timestamp
with the current time.
Create an Express.js application that uses middleware to handle 404 errors. The middleware should respond with a custom error message.
Remember, the key to mastering middleware (and Express.js in general) is through consistent practice and application of the concepts. Happy coding!