In this episode, we start refactoring our authentication logic to make it more reusable and maintainable by moving it into a composable. Rather than having our authentication state and functions scattered around or stuck in components, we centralize everything into a custom useAuth
composable.
First, we decide what should live in our auth state: the user's authentication status and their user data. We set up these state variables, and expose getters and setters for them. This helps us easily check if someone is logged in and access their info from anywhere in our app.
Next, we update our navigation component to pull auth data from the composable, so we can conditionally show the user's name or other content only when they're authenticated. As part of this, we also start planning for login
and other actions, adjusting our Home view to call a login
function from the composable.
We wire up the login flow, including loading the CSRF cookie with Axios and making a login request with error handling. We make sure to export all the necessary pieces from the composable so everything works as expected from our components.
Finally, we test it in the browser, confirming that our login is being handled by our new composable, and see that the setup is much cleaner and ready for future expansions. In the end, we note that there's still a bit of polish left to do—specifically splitting up the user-fetching logic and authentication state—which we'll tackle in the next episode.