This tutorial aims to provide a comprehensive understanding of how to use middleware for authentication and logging in a Node.js application. You will learn how to create middleware for authentication, log requests and responses, and protect your routes.
By the end of this tutorial, you will be able to:
- Create and use middleware in Node.js
- Implement authentication using middleware
- Log requests and responses using middleware
- Protect specific routes using middleware
Prerequisites:
- Basic understanding of JavaScript and Node.js
- Node.js and npm installed on your local machine
- Knowledge of Express.js would be beneficial but not mandatory
Middleware in Node.js is a function that has 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.
A middleware can be created using a function that accepts req, res, and next as parameters. Here is a simple logging middleware:
function loggingMiddleware(req, res, next) {
console.log(`Logged ${req.url} ${req.method} -- ${new Date()}`);
next();
}
Middleware functions are executed sequentially, therefore the order of middleware includes matters. Middleware can be applied for all routes or specific routes. Below is an example of applying middleware to all routes:
app.use(loggingMiddleware);
Authentication middleware can be created to protect routes. This middleware will check if there's a user in the request and if there isn't, it will stop the request from moving forward.
function authMiddleware(req, res, next) {
if (!req.user) {
res.status(403).send('You need to sign in.');
} else {
next();
}
}
Example 1: Applying Middleware to All Routes
app.use(loggingMiddleware);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
Example 2: Applying Middleware to Specific Routes
app.get('/private', authMiddleware, (req, res) => {
res.send('Welcome to the private page!');
});
In this tutorial, we learned about middleware in Node.js, how to create and use it. We also looked at how to create authentication middleware and how to apply middleware to all or specific routes.
For further learning, you can look into more complex applications of middleware for tasks like error handling and request body parsing.
Exercise Solutions:
1. Request counting middleware:
let requestCount = 0;
function countRequestMiddleware(req, res, next) {
requestCount++;
console.log(`Number of requests: ${requestCount}`);
next();
}
app.use(countRequestMiddleware);
function adminMiddleware(req, res, next) {
if (!req.user || req.user.role !== 'Admin') {
res.status(403).send('Only Admins can proceed.');
} else {
next();
}
}
app.get('/admin', adminMiddleware, (req, res) => {
res.send('Welcome, Admin!');
});