Search code examples
reactjscookiesfetchcross-domain

React app using API with another origin (CORS)


I have a react app, which uses a java ee backend rest server, running on another domain. I have enabled CORS:

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Headers : origin, content-type, accept, authorization
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age : 1209600

I am using react with fetch like this:

export function get(path, headers) {
    return fetch(apiUrl + path, {
        "metod" : "GET",
        "headers" : headers,
        "credentials" : "include"
    })
}

My react app is running on http://localhost:3000. When I am logging in, the server returns the Set-Cookie, but the cookie is not included in any further request to the server, unless I try to log in again. Then it is included for that specific login request.

Any suggestions?


Solution

  • So, I solved the problem by using another stackoverflow thread and robertklep's comment. As stated here: "When working on localhost, the cookie domain must be omitted entirely.". I implemented robertkleps idea, but did not set the domain. It resulted in a Set-Cookie like this: Set-Cookie:kek=7fukucsuji1n1ddcntc0ri4vi; Version=1; Path=/; Max-Age=100000. This works fine.