In this episode, we dive more into middleware and specifically set up the redirectIfAuthenticated
middleware. This middleware helps us out by redirecting users who are already logged in—so if someone is signed in and tries to visit the login or register pages, they’ll get pushed over to the dashboard instead. Makes things a bit more friendly and logical.
We start by cleaning up our middleware, removing the example one, and then adding redirectIfAuthenticated
to the login and register routes using the route's meta
middleware array. It's basically almost the same as our guest middleware, just flipped around.
After wiring it up, we test everything, but notice a little issue: even when signed in, users can still reach register and login. Turns out, it’s all about how the app initializes. The middleware doesn’t know about the user's authentication state yet, because routing happens before the auth check is done in main.js
.
We fix it by ensuring the router only boots once authentication has been checked. After this change, everything behaves as expected: authenticated users can't get to login/register and are pushed to where they belong. We wrap up by testing logging in, logging out, and hitting the dashboard. Everything's working smoothly!