Skip to content

React Node Unable to pass cookie to the browser (crocs error)

For some reason I am unable to store cookie in my browser.

This is the first time I am working with React And NodeJS

My React application is working on localhost:3000 and NodeJS application on localhost:8080

The Git repository for the same happens to be this

So, I am successfully able to login, store the credentials in DB and probably serialise and de-serialise.

I am not sharing the code for Google Strategy and serialise and de-serialise since I believe that problem doesn’t presist here (In case you think that you would need to view it click here

This Google redirect returns at following callback

   router.get("/google/callback", passport.authenticate('google', { failureRedirect: "/", session: false }), (req, res) => {


      res.redirect("http://localhost:3000/")
  })

In my server.js (main file, I start node server by doing node server.js), I am doing this to store cookie

app.use(cors({
  credentials: true,
  origin: ['http://localhost:3000'] // here goes any Frontend IP Adress
}))

//We are setting cookie here 
app.use(cookieSession({
  maxAge: 24*60*60*1000, //cookies is valid for a day
  keys: ['fgfhfjhfad'] 
}))  


app.use(passport.initialize())
app.use(passport.session())

And then when I do this in my react frontend

 componentWillMount() {
         axios.get("http://localhost:8080/",  {withCredentials: true}).then(response => {
             console.log(response)
         }).catch(error => {
             console.log(error)
         })
    }

Where my localhost:3000/ looks like this

app.get("/", (req, res) => {
  if (req.user) {
    if (req.isFormFilled) {
      res.redirect("http://localhost:3000/home")
    } else {
      res.json(req.user)
    }
  } else {
  res.json("user does not exsist")
  }
})

It always log res.json("user does not exsist") but if I directly go to localhost:3000 in my browser, I can see my req.user < [See: update below question]

Ps; I am enabling cross-origin request in my browser

[Question:] Can someone please help me in finding out what I could be doing wrong?

[Update:] It appears we might be having crocs error, I have changed my code and I am getting this as an error in frontend

Access to XMLHttpRequest at ‘localhost:8080’ from origin ‘localhost:3000’ has been blocked by CORS policy: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute

If I remove {withCredentials: true} in my axios request the above error disappears but then it logs user does not exsist in response.data

Answer

So send Cookies via REST its neccecary to:

Set Cors serverside:

app.use(cors({
    'allowedHeaders': ['sessionId', 'Content-Type'],
    'exposedHeaders': ['sessionId'],
    'credentials': true,
    'origin': ['http://[FRONTEND-IP]:[FRONTEND-PORT]', 'http://[ALTERNATIVE-FRONTEND-IP]:[FRONTEND-PORT]'],
}))

For Frontend you need to setup a call like this:

fetch('http://[API-IP]:[API-PORT]/call', {credentials: 'include'}).then((result) => {
    return result.json()
}).then((data) => {
    //Do something
});

you can also use fetch asynchronous:

async function loadData() {
    let response = await fetch(
        'http://[API-IP]:[APi-PORT]/call', 
        {credentials: 'include'}
    );
    return response.json();
}

this, of course, applies to using a rest service with json bodies. If you rely on another structure than json, you need to parse your response manually.

Also, An interested article on web about cors https://50linesofco.de/post/2017-03-06-cors-a-guided-tour