> For the complete documentation index, see [llms.txt](https://shoaib-1.gitbook.io/sirjuni/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shoaib-1.gitbook.io/sirjuni/middleware/applying-middleware.md).

# Applying Middleware

Making routes go through middleware before being sent to controllers.

When we define a route, we can apply a `middleware` to it, the request, then takes the path `Router` -> `Middleware` -> `Controller` rather than directly going to Controller from the Router. This can be used to put some routes behind authentication. To add authentication to routes, we can use `Auth` class provided in `sirJuni\Framework\Middleware\Auth` .  It is very simple to do using this framework, in code we just have to write

```php
Router::add_route('GET', '/admin', [AdminController::class, 'index'])->middleware(Auth::class);
```

If the user is authenticated using the `Auth::login()` method, about which you will learn in the `Auth` module, the user can visit `/admin` otherwise they will be redirected to the login page. Now, we need to tell `Auth` class where the login page is and we do that by `Auth::set_fallback_route('/path/to/login');`

<pre class="language-php"><code class="lang-php">use sirJuni\Framework\Middleware\Auth;   // add this line below the autoload.php

<strong>Auth::set_fallback_route('/login');     // if user visits /admin without authentication
</strong>// they will be redirected to /login
</code></pre>
