What if you could add a security check to all your routes with just one line of code?
Why Applying middleware to routes in NestJS? - Purpose & Use Cases
Imagine you have many routes in your app, and you want to check if a user is logged in before they can access certain pages. You try to add this check inside every route handler manually.
Manually adding the same check to every route is tiring, easy to forget, and makes your code messy. If you want to change the check, you must update every route separately, which wastes time and causes bugs.
Applying middleware to routes lets you write the check once and attach it to many routes automatically. This keeps your code clean and makes updates simple because the middleware runs before the route handlers.
app.get('/profile', (req, res) => { if (!req.user) return res.status(401).send('Login required'); /* handle profile */ });
app.use('/profile', authMiddleware); app.get('/profile', (req, res) => { /* handle profile */ });
You can easily add shared logic like authentication, logging, or error handling to many routes without repeating code.
A website requires users to log in before accessing their dashboard and settings pages. Middleware checks login status once and protects all these routes automatically.
Manual checks in every route are repetitive and error-prone.
Middleware runs shared code before routes, keeping code clean.
Applying middleware to routes makes maintenance and updates easier.