0
0
NestJSframework~3 mins

Why Functional middleware in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a few lines of middleware can save you hours of repetitive coding!

The Scenario

Imagine you have to check user permissions, log requests, and handle errors manually for every route in your NestJS app by repeating code everywhere.

The Problem

Manually adding these checks in each route is tiring, easy to forget, and makes your code messy and hard to maintain.

The Solution

Functional middleware lets you write small reusable functions that run before your route handlers, so you can add common logic cleanly and consistently.

Before vs After
Before
app.get('/data', (req, res) => { if (!req.user) return res.status(401).send('No access'); log(req); res.send('data'); });
After
app.use(authMiddleware); app.use(logMiddleware); app.get('/data', (req, res) => { res.send('data'); });
What It Enables

It enables you to keep your routes simple and focus on business logic while middleware handles shared tasks automatically.

Real Life Example

In a real app, you can add authentication middleware once, and it protects all routes without repeating code.

Key Takeaways

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.