Using Middleware for Authentication and Logging

Tutorial 4 of 5

1. Introduction

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

2. Step-by-Step Guide

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.

Creating a 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();
}

Using a Middleware

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);

Creating Authentication Middleware

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();
  }
}

3. Code Examples

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!');
});

4. Summary

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.

5. Practice Exercises

  1. Create a middleware function that counts the number of requests made to the server.
  2. Create an authentication middleware function that only allows requests with a 'Admin' role to proceed.

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);
  1. Admin role checking middleware:
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!');
});