0
0
Expressframework~30 mins

Conditional middleware execution in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional middleware execution in Express
📖 Scenario: You are building a simple Express server that handles requests differently based on a condition. Sometimes, you want to run a middleware only if a certain query parameter is present.
🎯 Goal: Create an Express server with a middleware that runs only when the request has a query parameter runMiddleware=true. Otherwise, the middleware should be skipped.
📋 What You'll Learn
Create an Express app with a GET route at /check
Create a middleware function called conditionalMiddleware
Use a variable shouldRun to check if the query parameter runMiddleware equals true
Apply the middleware only when shouldRun is true
Send a response with text Middleware ran if middleware ran, else Middleware skipped
💡 Why This Matters
🌍 Real World
Conditional middleware is useful when you want to apply certain logic only for specific requests, like authentication or feature toggles.
💼 Career
Backend developers often need to control middleware execution based on request data to build flexible and efficient APIs.
Progress0 / 4 steps
1
Set up Express app and route
Create an Express app by requiring express and calling express(). Then create a GET route at /check that sends the text Middleware skipped as response.
Express
Need a hint?

Use app.get('/check', (req, res) => { ... }) to create the route.

2
Add a variable to check query parameter
Inside the GET route at /check, create a variable called shouldRun that is true if req.query.runMiddleware equals the string 'true', otherwise false.
Express
Need a hint?

Use const shouldRun = req.query.runMiddleware === 'true' inside the route handler.

3
Create the conditional middleware function
Create a middleware function called conditionalMiddleware that takes req, res, and next as parameters. Inside it, send the response text Middleware ran. Do not call next() because this middleware ends the response.
Express
Need a hint?

Define function conditionalMiddleware(req, res, next) { res.send('Middleware ran') }.

4
Use the middleware conditionally in the route
Modify the GET route at /check to run conditionalMiddleware only if shouldRun is true. If shouldRun is false, send Middleware skipped as response. Use an if statement inside the route handler to decide.
Express
Need a hint?

Use if (shouldRun) { conditionalMiddleware(req, res, () => {}) } else { res.send('Middleware skipped') }.