'Separate React app and Laravel 8 api, doesnt set cookie/cors

I have a standalone react app on localhost:3000 using Axios I make a request to my Laravel 8 api using sanctum. The request goes through: enter image description here

But the cookie doesn't set. I found a thread here on stackoverflow and I made a Cors middleware and added http://localhost:3000 to allowed list, since before I had cors errors in console. Now the console is clean and I get the cookie in the request, it just doesn't get set.

My axios is configured like this:

   axios({
        method:'post',
    url:'http://localhost:8000/api/login',
    data:{
        'email':email,
        'password':password
    },
    
    headers:{
        'Access-Control-Allow-Origin': '*', 
        withCredentials:true,
        'Content-Type': 'application/json'
    }
})
.then(function(response){
    console.log(response.data);
})
.catch(function(error){
    console.log("error: " + error);
});

And handle in my laravel api:

public function handle(Request $request, Closure $next)
{
    return $next($request)
            ->header('Access-Control-Allow-Origin', 'http://localhost:3000')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Credentials', true);
}

My login method in authController:

    public function login(Request $request)
{
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
        $auth = Auth::user(); 
    $token = $auth->createToken('token')->plainTextToken;
    $response = response('Set Cookie');
    $response->withCookie(cookie('jwt', $token, 60));
    return $response;
} 
else{ 
    return $this->handleError('Unauthorised.', ['error'=>'Unauthorised']);
} 

}

Response cookie img: enter image description here enter image description here

As a note: I'm developing on Windows10 using "Xampp for Apache/MySql", "Composer" if that plays any role in such behavior.

Any suggestions what I need to change/do to get the cookie to my FE app? Is still cors the reason? How can I setup my local dev enviroment so I don't face such issues.



Solution 1:[1]

I had the same problem, and I found the solution, so you need to add {withCredentials:true} if you use Axios, and for fetch, add Credentials:include.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karl Hill