Search code examples
phplaravelcookieslaravel-sanctumfly

CSRF token mismatch error due to Laravel Sanctum not being able to set CSRF cookie in front end app


I have deployed two apps using https://fly.io/;

  • Laravel (v9) API backend
  • VueJS front end

Both apps are loading fine in the web browser.

The front end uses Laravel’s Sanctum library for authentication.

In the backend codebase, I have the following env values in the fly.toml file:

SANCTUM_STATEFUL_DOMAINS = ‘my-app.fly.dev’

SESSION_DOMAIN = ‘fly.dev’

However in the front end, the call to the endpoint /sanctum/csrf-cookie is failing to set the CSRF cookie needed for subsequent calls to the API. Upon inspecting the browser request header to set the cookies, the following error is given:

This attempt to set a cookie via a set-cookie header was blocked because its domain attribute was invalid with regards to the current host URL.

Having tried various different combinations of values for SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN, I am no closer to resolving the issue.

I have it working without issues in my local development environment with the following values:

  • SANCTUM_STATEFUL_DOMAINS=localhost:5173
  • SESSION_DOMAIN=localhost

Appreciate it if anyone can share some guidance on this.


Solution

  • Turns out my issue was because of the .fly.dev domain. The .fly.dev is shared between websites that don't have a custom domain so this would mean being able set cookies for other websites which is obviously a big no no. For a detailed explanation see here: https://community.fly.io/t/csrf-token-mismatch-error-due-to-laravel-sanctum-not-being-able-to-set-csrf-cookie-in-front-end-app/11580/10

    I was able to resolve the issue by using my own custom domain.