Middleware functions in Express.js 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.
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. 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.
Middleware functions are executed sequentially, and each middleware function has the ability to decide whether or not to pass control to the next middleware function in the stack by calling next(). If a middleware function does not call next(), the request will hang indefinitely.
In Express.js, middleware functions can be created and used in several ways:
Creating a custom middleware function is straightforward. A middleware function takes three parameters: req, res, and next. Here’s how you can define a simple custom middleware function:
1const myMiddleware = (req, res, next) => {2console.log('This is my custom middleware!');3next(); // Pass control to the next middleware function4};
Once you have defined a custom middleware function, you can use it in your Express application by calling app.use() and passing the middleware function as an argument. Here’s how you can do that:
1const express = require('express');2const app = express();34// Define a custom middleware function5const myMiddleware = (req, res, next) => {6console.log('This is my custom middleware!');7next(); // Pass control to the next middleware function8};910// Use the custom middleware function11app.use(myMiddleware);1213// Define a route14app.get('/', (req, res) => {15res.send('Hello World!');16});1718// Start the server19app.listen(3000, () => {20console.log('Server is running on port 3000');21});
When you run this code and navigate to http://localhost:3000, you will see the message "This is my custom middleware!" logged in the console, followed by "Hello World!" as the response from the server.
Let’s create a more practical example of a custom middleware function that checks if a user is authenticated before allowing access to certain routes. We’ll use a simple authentication mechanism where we check for a specific header value.
1const express = require('express');2const app = express();34// Define an authentication middleware function5const authenticate = (req, res, next) => {6const authHeader = req.headers['authorization'];7if (!authHeader || authHeader !== 'Bearer my-secret-token') {8return res.status(401).send('Unauthorized');9}10next(); // Pass control to the next middleware function11};1213// Use the authentication middleware for a specific route14app.get('/protected', authenticate, (req, res) => {15res.send('This is a protected route!');16});1718// Define a public route19app.get('/', (req, res) => {20res.send('Hello World!');21});2223// Start the server24app.listen(3000, () => {25console.log('Server is running on port 3000');26});
In this example, we have defined an authenticate middleware function that checks for a specific authorization header. If the header is missing or incorrect, it returns a 401 Unauthorized response. Otherwise, it calls next() to pass control to the next middleware function.
When you run this code and navigate to http://localhost:3000/protected, you will need to include the correct authorization header (Authorization: Bearer my-secret-token) in your request. If the header is missing or incorrect, you will receive a 401 Unauthorized response.
In the next section, we will explore how to handle asynchronous operations within middleware functions. This is particularly important when dealing with database queries or other I/O operations that require waiting for a response.
Stay tuned!