In this episode, we hit a little speed bump when trying to make API requests with Laravel Sanctum. First, we notice that our standard fetch requests from Nuxt are no longer working as expected after setting up authentication with Sanctum — we get a pesky 419 (page expired) status back! This happens because Sanctum uses a CSRF token (that it sets on first page load), and our fetch requests aren't automatically sending it.
To fix this, we switch to using the useSanctumClient
composable, which is designed to include the CSRF token with each request. From now on, anytime we need to talk to our Laravel API, we'll use this handy wrapper instead of the usual fetch, ensuring every request is properly authenticated.
We walk through updating our code, explaining why we can now drop the manual base URL (since it's already configured in our Nuxt/NUXT config) and showing that requests are now working, with the CSRF cookie being refreshed each time.
By the end of the episode, our API requests are flowing smoothly, setting us up for the next step: working with private event broadcasting. If you're scratching your head about 419 errors with Sanctum and Nuxt, this episode gets you back on track!