In this episode, we're tackling a key part of our authentication flow: attempting authentication. Instead of putting all our logic inside a single login method, we're creating a dedicated attempt
function inside our useAuth
composable. This separation helps keep things clean and makes it easier to fetch the user's details both after logging in and whenever we refresh the page.
Here's what we do step by step: we set up the attempt
function as an async method that tries to fetch the authenticated user from the /api/user
endpoint using Axios. If the request is successful, we update our state to show the user as authenticated and store their details. If it fails (like if the session expired), we reset everything back to the unauthenticated state, clearing out the user info.
We test this flow by logging in, making sure the user's name appears in the navigation when everything works, and explaining what happens if authentication fails. This way, when the app reloads, the correct state is shown—either keeping the user logged in or logging them out if something went wrong with their session.
By the end, you'll have a much smoother, more resilient authentication flow in your app!