In this episode, we walk through getting Laravel Sanctum set up and configured for authenticating a single-page application (SPA) with your Laravel API. We talk about why Sanctum's SPA mode is usually the best choice—it's more secure and keeps things simple, since we don't have to mess with tons of API tokens.
We start by installing Sanctum into our API project using the php artisan install api
command, which publishes the necessary files and migrations. Even though SPA auth doesn't really use personal access tokens, we still run the migration just to keep things tidy.
Next, we go through the Sanctum config, paying special attention to the stateful
domains section. This involves tweaking the .env
file to specify which domains are considered first-party (usually your API's and client's domains). We also set up Sanctum's middleware in the app's bootstrap file so it gets applied to our requests the right way.
After that, we set up CORS (Cross-Origin Resource Sharing), since a lot of API auth headaches are caused by missing or misconfigured CORS settings. We publish the CORS config, update its paths
to include authentication endpoints like /login
, and flip the supports_credentials
option to true
so cookies work across origins. We leave a note to add more paths later if we use other Fortify endpoints.
Finally, we confirm that our session domain is set up right in .env
, making sure cookies are scoped to the right domain, whether it's just api.test
or something with subdomains. With all this set up, our backend is ready for Laravel Sanctum authentication, and we're basically set to start sending requests and watching the magic happen!