In this episode, we dive into actually building out a real piece of middleware for our app! We start by introducing the idea of applying useful middleware to routes, and specifically, we create a redirectIfGuest
middleware. This middleware checks if the user is authenticated using our useAuth
composable. If the user isn't authenticated, we redirect them to the login page.
I break down how this works inside the middleware pipeline and explain how we use the next
function with route parameters to perform the redirection. You'll also learn why we don't need to import the router directly in the middleware, since we're already working within its context.
We test out our logic with some console logs and experiment with the order of middleware to see how the params propagate based on when a middleware decides to redirect. If one middleware causes a redirect, any others in the stack won't run—and that's exactly what we want!
So, by the end of this episode, you’ll have a working guest redirect middleware and a pretty solid understanding of how middleware chains operate and how routing and redirection flow within them.