Search code examples
javascriptcookiesfetchcross-domaincredentials

How to make the Browser include the cookies of the domain of the host origin when making a cross-origin HTTP request


I made a cross-origin HTTP request from the website 'demo.home.com' to 'demo.company.com' using the Fetch api with the credentials set to 'include'. There are two cookies. One is 'cookie_home=123; Domain=demo.home.com', the other is 'cookie_company=456; Domain=demo.company.com'. As a result, the cookie 'cookie_company' was included by the request. Is there any way to let the cookie 'cookie_home' be included by the request?

// the request is made in the website 'http://demo.home.com'
// the cookies are:
// 'cookie_home=123; Domain=demo.home.com'
// 'cookie_company=456; Domain=demo.company.com'
fetch('http://demo.company.com/api/test', {
    method: 'GET',
    credentials: 'include'
});

Solution

  • You can't. fetch (and XMLHttpRequest) provide no mechanism to manually set cookies in a request.

    They'll only send cookies in the browser's cookie jar for the target URL. This applies the normal rules for which domain a cookie belongs to.

    You need to use some other mechanism to send the data you would store in the cookies.