0
0
Expressframework~5 mins

Conditional middleware execution in Express

Choose your learning style9 modes available
Introduction

Sometimes you want middleware to run only for certain requests, not all. Conditional middleware helps you control when middleware runs.

Run authentication only on protected routes.
Log requests only for specific URL paths.
Apply rate limiting only for API endpoints.
Skip middleware for static files like images or CSS.
Syntax
Express
app.use((req, res, next) => {
  if (condition) {
    middlewareFunction(req, res, next);
  } else {
    next();
  }
});

The next() function passes control to the next middleware.

Check your condition inside the middleware to decide whether to run the middleware logic or skip it.

Examples
This middleware logs only requests starting with '/api'.
Express
app.use((req, res, next) => {
  if (req.path.startsWith('/api')) {
    console.log('API request');
  }
  next();
});
This middleware runs only for POST requests.
Express
app.use((req, res, next) => {
  if (req.method === 'POST') {
    console.log('POST request received');
  }
  next();
});
This runs authentication only on routes starting with '/private'.
Express
const authMiddleware = (req, res, next) => {
  if (req.headers.authorization) {
    next();
  } else {
    res.status(401).send('Unauthorized');
  }
};

app.use((req, res, next) => {
  if (req.path.startsWith('/private')) {
    authMiddleware(req, res, next);
  } else {
    next();
  }
});
Sample Program

This Express app uses conditional middleware to log only requests to paths starting with '/api'. Other requests skip the log.

Express
import express from 'express';

const app = express();

// Middleware that logs only API requests
app.use((req, res, next) => {
  if (req.path.startsWith('/api')) {
    console.log(`API request to ${req.path}`);
  }
  next();
});

// Simple route
app.get('/api/data', (req, res) => {
  res.send('Here is your API data');
});

app.get('/', (req, res) => {
  res.send('Welcome to the homepage');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always call next() to avoid hanging requests.

Conditions can check path, method, headers, or any request property.

Use this pattern to keep middleware efficient and avoid unnecessary work.

Summary

Conditional middleware runs only when you want it to.

Use if checks inside middleware to decide execution.

Always call next() to continue request handling.