I have a question for the use of Laravel Sanctum for authentication. It's about the commonly stated rule that the SPA (Single Page Application) and Laravel API must be on the same top-level domain for Sanctum to function correctly.
My understanding of this is that for Sanctum to work properly, the front end and back end must always be on the same top-level domain, whether in production or development. This is typically achieved by having a subdomain for either the SPA or Laravel API.
However, I find myself in a situation where I'd like to host my backend on a server while still enabling requests from a frontend that would inevitably be on a different domain (for the purpose of other developers).
Is there a viable workaround for such a scenario when using Laravel Sanctum for authentication?
form sanctum docs:
Laravel Sanctum common mistakes
MISTAKE 1. NOT USING THE SAME TOP-LEVEL DOMAIN
Your SPA and Laravel API must be on the same top-level domain. You cannot have your SPA at domainA.com and the Laravel API at domainB.com. You also cannot have app.test and localhost:3000.
But why? you might ask. The answer is because laravel/sanctum, the recommended Laravel authentication package for SPAs, works by setting up an HttpOnly, Lax cookie. This cookie is secure, it cannot be read or stolen, but most importantly, it cannot be shared across different domains. And this is why you must have your frontend and backend on the same top-level domain. Usually, you would have a subdomain either for the SPA or Laravel API.
Whether in production or development, your Laravel API and SPA must always be on the same top-level domain.
the front end and back end must always be on the same top-level domain
That is if you want to use sessions instead of tokens.
Sanctum offers 2 features, to authenticate using cookies (regular cookie-based auth) or token-based auth, but you can use whatever works for you best (based on your use-case).
The docs:
It is perfectly fine to use Sanctum only for API token authentication or only for SPA authentication. Just because you use Sanctum does not mean you are required to use both features it offers.
So I guess what you are looking for is tokens auth instead.
Just make sure to add your frontend domain to the CORS configuration (configure your first party domains), this way the browser won't block the responses of your backend server.