Discover how a few lines of middleware can save you hours of repetitive coding!
Why Functional middleware in NestJS? - Purpose & Use Cases
Imagine you have to check user permissions, log requests, and handle errors manually for every route in your NestJS app by repeating code everywhere.
Manually adding these checks in each route is tiring, easy to forget, and makes your code messy and hard to maintain.
Functional middleware lets you write small reusable functions that run before your route handlers, so you can add common logic cleanly and consistently.
app.get('/data', (req, res) => { if (!req.user) return res.status(401).send('No access'); log(req); res.send('data'); });
app.use(authMiddleware); app.use(logMiddleware); app.get('/data', (req, res) => { res.send('data'); });
It enables you to keep your routes simple and focus on business logic while middleware handles shared tasks automatically.
In a real app, you can add authentication middleware once, and it protects all routes without repeating code.
Manual checks in routes cause repetition and errors.
Functional middleware runs shared code before routes.
This keeps your app clean, consistent, and easier to maintain.