How to Use Middleware for Specific Route in Express
In Express, you use
app.use() or route methods like app.get() with middleware functions as arguments before the route handler to apply middleware to specific routes. This way, the middleware runs only when requests match that route.Syntax
To apply middleware to a specific route, place the middleware function(s) as arguments before the route handler in the route method.
Example parts:
app.get('/path', middlewareFunction, handlerFunction): Middleware runs only for GET requests to '/path'.middlewareFunction: Function that processes the request before the handler.handlerFunction: Final function that sends the response.
javascript
app.get('/route', middlewareFunction, (req, res) => { res.send('Response after middleware'); });
Example
This example shows a middleware that logs request info only for the '/user' route. Other routes are unaffected.
javascript
import express from 'express'; const app = express(); // Middleware to log request method and URL const logMiddleware = (req, res, next) => { console.log(`Request Method: ${req.method}, URL: ${req.url}`); next(); }; // Apply middleware only to '/user' route app.get('/user', logMiddleware, (req, res) => { res.send('User page with logging middleware'); }); // Route without middleware app.get('/', (req, res) => { res.send('Home page without middleware'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Request Method: GET, URL: /user
Common Pitfalls
1. Applying middleware globally instead of per route: Using app.use(middleware) applies middleware to all routes, which may be unintended.
2. Forgetting to call next() in middleware: This blocks the request and the handler never runs.
3. Middleware order matters: Middleware must be placed before the route handler in the argument list.
javascript
/* Wrong: Middleware applied globally unintentionally */ app.use(logMiddleware); app.get('/user', (req, res) => { res.send('User page'); }); /* Correct: Middleware applied only to '/user' route */ app.get('/user', logMiddleware, (req, res) => { res.send('User page'); });
Quick Reference
- Use
app.METHOD(path, middleware, handler)to add middleware to a specific route. - Middleware functions receive
req, res, nextand must callnext()to continue. - Order matters: middleware must come before the handler.
- Use multiple middleware by listing them before the handler.
Key Takeaways
Place middleware functions as arguments before the route handler to apply them to specific routes.
Always call next() inside middleware to pass control to the next function.
Middleware order matters; it must come before the route handler in the argument list.
Use app.use() for global middleware and route methods for route-specific middleware.
You can add multiple middleware functions to a single route by listing them in order.