Search code examples
node.jsreact-nativefetchexpress-session

fetch has no session in second call in React-Native on NodeJS backend


First task my application does on startup is to make a POST call to the endpoint /handshake with an access token to authorize.

Node backend checks if the session variable req.session.uid is already set. Otherwise it'll check the access token from the POST body and sets the req.session.uid on valid access token.

It works properly when testing in Postman. Doing an API-Call after a successfull /handshake found place beforehand uses the req.session.uid within the request.

Unfortunately using fetch() in react-native shows an odd behavior, when session already existed before.

Case (No Session Exists):

  1. /handshake with correct access token => backend sets req.session.uid
  2. Every other call on the API works and uses the previously set uid.

Case (Session Already Exist):

  1. /handshake with correct access token => backend sets no variable since req.session.uid is already set.
  2. Making another API call => req.session.id is undefined

I thought the issue may relate to issues in other api calls and tried to send another /handshake request when the first one succeeds:

  1. /handshake with correct access token => backend sets no variable since req.session.uidis already set.
  2. /handshake with correct access token => backend sets req.session.uid since it is undefined

Every call after the second /handshake works properly. The main question here is, why does the backend recognizes me in the first /handshake call and does not when trying to make the second call?

Here is the code where /handshake request is called:

       fetch(this.Links.handshake, 
            {body: myBody, method:"POST", credentials: "include",
            headers:{ 'Content-Type' : 'application/x-www-form-urlencoded'}})
       .then((response) => {
            if(response.ok)
                console.log("Handshake was successfull");
            else
                console.warn("Handshake failed ("+response.status+")!");
        }).catch(() => {
            console.warn("Error happened while handshake...");
        })

Solution

  • This issue was related to the cookie being deleted after the first call. I solved my issue by saving the cookie header by myself (saving the Set-Cookie header from the first request method and sending it with the 'cookie' header).