How do I add middleware to a single route?
Routing Mar 7, 2026

How do I add middleware to a single route?

Asked by Dev Advocate

I want to protect one endpoint without adding a global middleware. What is the recommended approach?

Answers

2 total
Ademola Ibukun
Feb 9, 2026
this is nice
Ademola Ibukun
Feb 9, 2026
### 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.

Your Answer

Signed-in users with contributor, admin, or dev roles can submit answers.

You need to sign in to post an answer.