So far we’ve used app.use() to apply middleware to all routes. But you can also apply middleware in other ways:

1. Apply middleware to specific routes

Instead of using app.use() to apply middleware to all routes, we can create a middleware function and pass it to specific routes. Here’s how:

Step 1: Create a middleware function

// Middleware function
function logRequest(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

Step 2: Pass the function to specific routes

// Apply to one route
app.get("/users", logRequest, (req, res) => {
  res.json({ users: [] });
});

Notice how we pass logRequest (the function name) as a parameter between the route path and the route handler. This middleware will only run for requests to /users.

2. Apply middleware to multiple routes

You can apply middleware to all routes that start with a specific path using app.use() with a path parameter:

Step 1: Use the middleware function with a path

// Apply to all routes that start with /api
app.use("/api", logRequest);

Step 2: Create routes that match the path

app.get("/api/users", (req, res) => {
  res.json({ users: [] });
});

app.get("/api/products", (req, res) => {
  res.json({ products: [] });
});

Now the logRequest middleware will run for both /api/users and /api/products (and any other routes starting with /api).

3. Apply multiple middleware to one route

You can apply multiple middleware functions to a single route by passing them as separate parameters. They will run in the order you list them:

Step 1: Create multiple middleware functions

function checkAuth(req, res, next) {
  // Check if user is logged in
  next();
}

function logRequest(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

Step 2: Pass multiple middleware to one route

// Both middleware run before the route handler
app.get("/admin", checkAuth, logRequest, (req, res) => {
  res.json({ message: "Admin page" });
});

Execution order: checkAuthlogRequest → route handler. Each middleware must call next() to continue to the next one.



Repo link

Tags: