Blog>
Snippets

Conditional Middleware Execution

Demonstrate how to conditionally execute middleware based on the route or other criteria.
const express = require('express');
const app = express();

// A middleware that logs the request method and URL
function loggingMiddleware(req, res, next) {
    console.log(`Request Type: ${req.method}, URL: ${req.originalUrl}`);
    next();
}

// A middleware that only runs on POST requests
function postRequestMiddleware(req, res, next) {
    if (req.method === 'POST') {
        // Perform some action specific to POST requests
        console.log('This middleware is only for POST requests');
    }
    // Continue to next middleware
    next();
}

// Use the logging middleware for all routes
app.use(loggingMiddleware);

// Use conditional middleware for the '/submit' route
app.use('/submit', postRequestMiddleware);

// Example route
app.get('/', (req, res) => {
    res.send('Hello World!');
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
This code sets up an Express.js server with two middlewares. The loggingMiddleware is applied globally and logs every request. The postRequestMiddleware checks if the incoming request is a POST request and logs a message if true; it's conditionally applied only to the '/submit' route.