### Protecting a Single Route with Middleware
If you want to protect **only one endpoint** (not globally), there are **two recommended approaches**, depending on how your route is defined.
---
## 1️⃣ Using a Controller (Controller-level middleware)
If your route points to a controller method, attach the middleware **directly to that method**.
```dart
router.get(
'/profile',
AuthMiddleware.handle(UserController.index),
);
```
### ✅ When to use this
* Your logic lives in a controller
* You want explicit protection on specific controller actions
* Clear and readable in larger applications
This approach keeps the middleware close to the controller action and avoids affecting other routes.
---
## 2️⃣ Using the Route Builder (Inline middleware)
If your route logic is written inline (without a controller), use `.useMiddleware()` on the route builder.
```dart
router
.get('/profile', (req, res) {
return res.json({'message': 'Protected route'});
})
.useMiddleware(AuthMiddleware());
```
### ✅ When to use this
* Simple or inline route handlers
* Quick protection without creating a controller
* Fine-grained control per route
---
## ✅ Recommended Practice
* **Controllers →** wrap the controller method with `AuthMiddleware.handle(...)`
* **Inline routes →** use `.useMiddleware()` on the route
This keeps your middleware **scoped, explicit, and predictable**, without introducing unnecessary global behavior.