Kunok
Kunok

Reputation: 8769

Losing cookies in headers when sending HTTP request to other domain

I have a client hosted on one domain app.example.com and a API server on other subdomain api.example.com. In development mode there are localhost:3000 and localhost:4000.

I am trying to send HTTP requests that include Cookie header. This worked just fine while everything was on the same server and domain. Then I changed code and added CORS also included withCredentials property on Axios HTTP library. In development mode it works, cookies are sent in requests, however in production this breaks. All requests seem to work fine, both OPTIONS and followed POST requests get 200ish response.

This is my CORS setup on the API server:

server.all('/*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', DEV ? 'http://localhost:3000' : 'https://example.com')
    res.header('Access-Control-Allow-Headers', '')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('Access-Control-Allow-Credentials', 'true')
    next()
  })

and this is how my axios requests look like:

axios(`${API_URL}/someEndpoint`, {
    method: 'post',
    withCredentials: true,
    data,
  })

However my requests do not include Cookie headers:

enter image description here

Then I came across this post and answers say its impossible to share cookies among domains. Now I am extremely confused.

I use cookies in my headers to detect which user sends which request. If I lose cookies in headers I can no longer track which request was sent by which (not logged in) user and therefore I can't aggregate this data for statistics anymore.

My application was monolith but I had to separate API server from render server. Is it possible to still read cookies in headers even tho servers use different domains?

Upvotes: 0

Views: 1547

Answers (1)

Kunok
Kunok

Reputation: 8769

It appears that sharing cookies this way among different domains is rather impossible ~ security risk, however in question it was also mentioned sharing among subdomains and that is possible by adding domain property while setting cookie.

cookies.set('cookieName', 'cookieValue' , { path: '/', domain: DEV ? undefined : '.example.com' })

Note that value starts with .

Meanwhile, workaround for sending cookie values among different domains would be sending custom headers with cookie values.

Upvotes: 1

Related Questions