0
0
NestJSframework~3 mins

Why Applying middleware to routes in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add a security check to all your routes with just one line of code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
app.get('/profile', (req, res) => { if (!req.user) return res.status(401).send('Login required'); /* handle profile */ });
After
app.use('/profile', authMiddleware); app.get('/profile', (req, res) => { /* handle profile */ });
What It Enables

You can easily add shared logic like authentication, logging, or error handling to many routes without repeating code.

Real Life Example

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.

Key Takeaways

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.