In this episode, we set up basic authentication for our Nuxt frontend talking to a Laravel backend, using Laravel Sanctum for API authentication with cookies. The driving goal is to make sure that our users can sign in, which is a must before we start working with private channels and real-time features.
Here's what happens step-by-step:
- We start by quickly creating a user in the database using the Laravel user factory. By default, the password is just
password
.
- Next, we install Laravel Fortify, a package that gives us all the API endpoints we need for authentication (login, logout, etc.). We pull it in, run its install command, and check out the new routes it gives us.
- Then, we tune our Sanctum and application config a bit. This includes setting up the session domain, configuring the Sanctum stateful domains to include both the backend and frontend origins (including the client port), and publishing the CORS config to support credentials and allow the correct paths (like Fortify's login and logout routes).
- After some quick middleware tweaks (so that API state works as expected), we turn to the client side. We pull in the
Nuxt Laravel Sanctum
module, point it at our backend API, and get ready to actually make requests.
- On the Nuxt frontend, we scaffold a super basic nav component with login and logout buttons. No fancy form yet — just hard-coded credentials for now so you can quickly test the flow. Using the provided composables (
useSanctumAuth
), we wire up login, logout, checking if a user is authenticated, and display the logged-in user's name.
- Finally, we test it in the browser and see that our sign-in and sign-out flow is working: clicking "Sign In" exchanges cookies, gets our user from the API, and lets us see that info right there in the UI. Sign out works the same way.
Now that authentication is working, we're set up to move onto the real goal: sending and listening to events on private channels. Onward!