Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

usanzadunje's avatar

Setting same_site in seasson.php doesnt do anything

Whenever I try to login I see that cookie from Laravel has samesite=lax. Since my backend and frontend are on different domains, I hosted backend and my frontend is in localhost now, cookie cannot be set because samesite=lax;

This is easy to solve simply by setting samesite=none. But when I set 'same_site' => 'none' in seasson.php and tried again I still have same thing samesite=lax.

I even tried to set it from Nginx configuration by : proxy_cookie_path / "/; secure; HttpOnly; SameSite=none"; and that still didn't solve it. This is so frustrating since I do not know where this samesite=lax comes from, I set it from Laravel and even Nginx configuration to be samesite=none but it still isn't.

Any help is appreciated!

0 likes
40 replies
jlrdw's avatar

Did you

php artisan config:clear

after changes, and restart server.

usanzadunje's avatar

I tried that, problem is still there samesite=lax every time.

I did a test where i put secured=false and it really did remove that attribute. But in same config/session.php when I put samesite=none it doesn't change it.

I don't know what could be overriding it to =lax every time.. :/

EDIT: Even when I set samesite => 'strict' it doesn't change it to strict.

usanzadunje's avatar

Already have that and CORS configured with Laravel Sanctum.

I don't understand what could be overriding it. Since I put samesite => 'none' from Laravel session.php config and I added it in my NGINX configuration as well.

What else could be changing this back to samesite=lax?

Also tried another browser, same thing there.

Once I put database driver and tried logging in again I saw that sessions table was getting populated but still when I inspect network from Chrome Dev Tools I see error that Set-Cookie was blocked because samesite=lax.

Screenshot of error: https://prnt.sc/16df88k

EDIT: Will comment again once I check issues.

usanzadunje's avatar

Checked issues, nothing there helped. I searched around more without any success.

Is there something that is for sure gonna override this setting so I can set it there?

It seems to me like 'samesite' => 'none' from Laravel config isn't doing anything it doesn't even change for strict, but other attributes like secured are changing

usanzadunje's avatar

I didn't really cache anything explicitly myself.

I read the article and it gave some ideas but it didn't work unfortunately.

I have supports_credentials set to true and in article it says :

supports_credentials allows sending cookies and sessions (which rely on cookies also) over CORS requests. It sets the Access-Control-Allow-Credentials and cannot be true when all origins are allowed (i.e., when allowed_origins is the wildcard (*) character).

So I explicitly set allowed_origins to my local address, still no success there.

I went ahead and looked one error ,this one is saying :

Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request.

Maybe its false error but how can SameSite attribute not be set...

jlrdw's avatar

Since you have different domains, have you tried to setup the backend as an api and use api routes.

usanzadunje's avatar

Yrah, actually whole Laravel project is set to be API only. Every route is in api.php except ones comming from Laravel Fortify, which i used for authentication.

usanzadunje's avatar

Maybe I said it wrong.

I have Laravel backend communicating with my application via API calls.

I am using Ionic with Vue.js to build native mobile apps that will communicate with my Laravel backend for information. Also when testing Ionic provides server so I can test my app in browser ,that's how I saw why cookie is not being set.

When I first started this project I thought it was gonna be full Vue.js SPA so I went with Laravel Sanctum and Fortify for my authentication part. I was thinking of changing to token based authentication but I stuck with session based since that was working just fine.

Would you suggest me to change it to token based authentication since I already use Laravel Sanctum? I would just generate token for mobile users and store it somewhere on their device and then send it every time I need authorized access from them(correct me if I am wrong)?

As for Sanctum I am pretty sure everything is set okay since I had many problems and red dozen of articles about it.

Also, thank you so much for taking your time to help me I really appreciate it!!!

jlrdw's avatar

frontend is in localhost now

Maybe try putting frontend on server as well, at least put on server long enough to see how it will work.

Is frontend currently on a dedicated server? Or do you mean your local development server? Are you mixing any http and https, which won't work, but thought I'd ask.

usanzadunje's avatar

Frontend is not on dedi server it is on my local machine.

However i build native apk and install app on android, that is my 'frontend'. And it doesn't work even in that case.

As for server i mentioned it is if you want web app with Ionic which I do not. I only use it for easier development.

My backend is on https but frontend is served as either localhost:8100 which should be like https(i think) or computer ip:8100 which is on http. I will double check tomorrow for that.

Will cookie not be set if my backend is on https and I talk to it from http? Could that cause samesite to always be set to lax?

themsaid's avatar

samesite cannot be set to none unless you set session.secure = true in your config file and serve the site over HTTPS.

usanzadunje's avatar

Backend is on HTTPS and I set secure to true. It is always defaulting to lax.

themsaid's avatar

Your app is broken somewhere. A fresh Laravel app works fine and sends the correct value for the SameSite policy.

usanzadunje's avatar

I guess, I will start new Laravel project and copy everything there.

Will give more info once I've done that.

Hellocode's avatar

You try set inside config/session.php

// You can inject it into the cookie through the path argument.
'path' => env('APP_ENV') === 'local' ? '/' : '/;samesite=none',

'secure' => env('APP_ENV') === 'local' ? false : true,
usanzadunje's avatar

It is setting it but something else is also setting it to lax.

https://prnt.sc/17tij6v

I have never configured this setting ever before in my app, i do not know what could be causing this.

I am probably going to start new Laravel app and copy everything over. That is something I haven't tried, also it could help refactoring code so I am defenetely going to do it.

Hellocode's avatar

All setting in here


// Laravel Framework 8.49.0
// Path vendor/laravel/framework/src/Illuminate/Cookie/CookieServiceProvider.php

// code 

 public function register()
    {
        $this->app->singleton('cookie', function ($app) {
            $config = $app->make('config')->get('session');

            return (new CookieJar)->setDefaultPathAndDomain(
                $config['path'], $config['domain'], $config['secure'], $config['same_site'] ?? null
            );
        });
    }

usanzadunje's avatar

I set it manually there to None and session cookie still had SameSite=lax

I think it's best for me to just start over and see if error happens on fresh install.

I will give updates.

usanzadunje's avatar
usanzadunje
OP
Best Answer
Level 3

FINAL UPDATE

I was not able to change SameSite policy to None, I have tried all solutions these kind people suggested.

I think that @themsaid is right and my app is broken somewhere.

I decided to start authentication from scratch and since this backend only serves mobile(android and iOS) apps, made in Ionic, I decided not to make it session based as it previously was but to go with token based authentication. I used Laravel Sanctum still but I ditched Laravel Fortify and made my own authentication logic.

I should have done this from start since this is better approach for authenticating mobile apps(in my opinion) and gives way less problems.

Problem for me was at the start of developing this whole project I thought I was going to have SPA application and didn't quite understand how Ionic works and I went with session based authentication.

Lesson here: Think VERY carefully what and how you need to implement, also don't code something only because it works because later it might not be the best choice, this can save you from wasting time on going back and trying to change/fix it like I had to in my case.

Also want to thank all the people that helped here, it really is a great community here on Laracasts!

CLOSED!

vikasaroy's avatar

I am trying something similar. I have Laravel App hosted on Vapor. I am using only API routes. I am using sanctum for auth.

I am trying to call the API from a react app running locally on my machine.

Somehow the set-cookie header is getting rejected due to samesite=lax. I am getting the following error:

The attempt to set cookie via set-cookie is blocked because its domain attribute is invalid with regards to the current host URL.

Is there a way to get a local react app to work with a remote Laravel?

usanzadunje's avatar

@vikasaroy It is rejected because your frontend is on localhost and your API is hosted therefore they don't have same domain. Try some of steps people provided here to set samesite to none. Otherwise put your frontend on same domain your backend is and you should not have this problem.

I think I was not getting that exact error so I suggest you search around for it, maybe somebody had that exactly and it will help you better.

Good luck!

daniti's avatar

How did it go in the end? I'm in a similar situation but I didn't use Fortify. I have separate frontend and backend and everything is working fine locally, but on the server, session and XSRF-token cookies always have Lax 🤔

2 likes
fvaresi's avatar

@daniti it's sanctum middleware... for some reason it's forcing 'lax' value. Check EnsureFrontendRequestsAreStateful. If you figure out why they are forcing this value please let me know.

1 like
usanzadunje's avatar

@daniti I just switched to token auth. As it was more suitable for my type of application as well.

1 like
daniti's avatar

@fvaresi I'm using Sanctum indeed, but are you sure that's the culprit? Wouldn't it behave the same locally? 🤔 Edit: I tried overwriting that class forcing it to none. I’m still having CSRF issues, So I guess my problem is actually somewhere else…

yoroshikudozo's avatar

Finally I manage to authenticate remote sanctum server from local.

I cannot set samesite=none at laravel sanctum, so I deceive into my browser as if it is a valid request.

My env:

server: laravel with Sanctum stateful auth
local: vue2 devServer (webpack 4)
PC: mac os

1. Set devServer settings to vue.config.js

module.exports = {
  devServer: {
    https: true,
    disableHostCheck: true,
    public: "local.myapp.com",
    port: 443,
  }
}
  1. Use https to set X-XSRF-TOKEN in axios request headers
  2. Set port to default https port (443)
  3. Set public with same value in LARAVEL_SANCTUM_STATEFUL_DOMAINS

2. Edit LARAVEL_SANCTUM_STATEFUL_DOMAINS

LARAVEL_SANCTUM_STATEFUL_DOMAINS=local.myapp.com

3. Add withCredentials to vue axios setting

const instance = axios.create({
  withCredentials: true,
})
const fetchToken = instance.get("/csrf-token")
const login = (data) => fetchToken().then(() => instance.post("/login", data))

4. Edit hosts file to deceive my browser referer .

sudo vi /private/etc/hosts

And, add

127.0.0.1 local.myapp.com

5. Start vue local devServer with sodo

sudo npm run serve:local

If you want to use a port number lower than 1023, you have to add sudo command. If it fails, check your nodejs version. It works well in node v12, not works in v14.

Access browsers with ht tps://local.myapp.com

If you fails, check below points that I found.

  1. I cannot overwrite samesite at Laravel Sanctum in a normal way.
  2. I seem that X-XRSF-TOKEN is automatically set only when I use https .
  3. I have to set port: 443 in vue.config.js to access devServer without port.
  4. Request referer must contain in LARAVEL_SANCTUM_STATEFUL_DOMAINS , so I have to set public in vue.config.js.
  5. I have to edit /private/etc/hosts to access with custom domain in a browser.

Hope this comment will help you.

taylorbrontario's avatar

Yes, Sanctum overrides the 'same_site' cookie attribute in HTTP responses.

After following all installation instructions for Sanctum, you should have the Sanctum middleware "\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class" added inside in your Laravel app kernel file located at ''App\Http\Kernel.php''. This Sanctum middleware calls the following function (defined inside EnsureFrontendRequestsAreStateful.php) during its execution:

protected function configureSecureCookieSessions()
    {
        config([
            'session.http_only' => true,
            'session.same_site' => 'lax',
        ]);
    }

"config" is a laravel helper function that sets configuration values for the current HTTP request

I found this by searching for the term 'lax' inside Visual Studio Code. You may have missed this because VS Code does not search vender files by default. To enable searching vendor files in VS Code: 1) Go to File > Preferences > Settings 2) Search for "Search: Use Ignore Files" 3) Disable the setting "Search: Use Ignore Files"

I don't know why Sanctum middleware does this. My guess is that Sanctum devs wanted to provide a default level of security for Sanctum users.

taylorbrontario's avatar

After much frustration trying to deal with SPA authentication with a Cordova front end, I have decided to adopt a separate authentication system for my mobile app using Sanctums API tokens. See the "Mobile Application Authentication" section on the Laravel Sanctum official doc page.

My web app will continue using Sanctum's cookie based authentication. I don't work on my project full time, but I've probably spent the better part of a month trying to get Cordova + Sanctum to work together, trying Cordova plugins to access the cookies and not being able too. I have no more hair left to pull out :) Anyways, I hope the road isn't too bumpy from here on out.

farsad's avatar

For people coming from Ionic + Something who are using Fetch instead of Capacitor's built-in HTTP, you can create an additional middleware as follows:

<?php

namespace App\Http\Middleware;

class EnsureFrontendRequestsAreStateful extends \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful
{
    protected function configureSecureCookieSessions(): void
    {
        config([
            'session.http_only' => true,
            'session.secure' => true,
            'session.partitioned' => true,
            'session.same_site' => 'none',
        ]);
    }
}

Then use it as a replacement in your Kernel.php file instead of the Sanctum one.

    protected $middlewareGroups = [
        // Whatever is here

        'api' => [
            \App\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            // Whatever is here
        ],
    ];

PS: session.partitioned is optional; however, Google Chrome will drop support for cross-site cookies. Better be safe than sorry.

Edit: After many trial and errors, seemingly Capacitor for iOS doesn't properly support cookies. If you're planning to use your app on iOS devices, there are hacky ways to get around this; however, the cookie storage can and might be deleted frequently.

1 like
clairemira's avatar

I had the same issue where changing the same_site attribute in config/session.php wasn't working and cookies kept getting set as lax even when trying all other options. I looked into it and in my case it was due to using the EnsureFrontendRequestsAreStateful middleware from Sanctum. If you look inside the middleware you will see the configureSecureCookieSessions function which overrides both session.http_only and session.same_site.

I had a unique case where I needed this to be set to none on localhost but I still required the EnsureFrontendRequestsAreStateful middleware, so I just created my own middleware extending Sanctum's and overriding the configureSecureCookieSessions accordingly, to conditionally set as 'none' when on localhost. I hope this helps anyone as it stumped me for a bit!

3 likes
chupacabramiamor's avatar

@clairemira Exactly is the true only way if you are using Sanctum as the cookie-based auth scheme. It's so a EnsureFrontendRequestsAreStateful middleware creates a mistake around the user session configuration, overriding them by own one.

You answer must be going to the best answer! :)

juani981's avatar

@clairemira Thank you very much, this was the only reason for the problem, been strugling for days

Please or to participate in this conversation.