CORS Cookie not set on cross domains, using fetch, set credentials: ‘include’ and origins have been set Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of CORS Cookie not set on cross domains, using fetch, set credentials: ‘include’ and origins have been set without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m using fetch to do a request to the backend. The cookie ISN’T set when I use a different domain. The cookie IS set when I use the same domain.

Why is it not being set?

I modified my /etc/hosts file to use pseudonymns to test using the same and different domain, and made sure they are not blacklisted by the browser either.

If I use local-test-frontend.com for both the browser and server domain it works, but if I change the backend url to local-test-backend.com it fails.

*Note that my front end url I test it from is * http://local-test-frontend.com:3000/login

Javascript

    fetch('http://local-test-backend.com/login',  {
        mode: 'cors',
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginRequest),
        credentials: 'include'
    }).then(// Other code here.....

Server Response Headers

Access-Control-Allow-Credentials    
true
Access-Control-Allow-Origin 
http://local-test-frontend.com:3000
Content-Length  
103
Content-Type    
application/json
Date    
Wed, 10 Jul 2019 07:23:49 GMT
Server  
Werkzeug/0.15.1 Python/3.7.3
Set-Cookie  
MY_TOKEN=a7b8ad50f19…end.com; Path=/; SameSite=Lax

Answer

I’m just trying to get a cookie set for my current domain by calling a server on a different domain.

You can’t, at least not directly. Cookies belong to the origin that set them.

The closest you could come would be for the different domain to return the data in a non-Cookie format (such as the body of the response), and then to use client-side JS to store it using document.cookie.

We are here to answer your question about CORS Cookie not set on cross domains, using fetch, set credentials: ‘include’ and origins have been set - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji