question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Response cookies not being set

See original GitHub issue

I’m trying to implement client login using fetch on react.

I’m using passport for authentication. The reason I’m using fetch and not regular form.submit(), is because I want to be able to recieve error messages from my express server, like: "username or password is wrong".

I know that passport can send back messages using flash messages, but flash requires sessions and I would like to avoid them.

This is my code:

    fetch('/login/local', {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: this.state.username,
            password: this.state.password,
          }),
        }).then(res => {
          console.log(res.headers.get('set-cookie')); // undefined
          console.log(document.cookie); // nope
          return res.json();
        }).then(json => {
          if (json.success) {
            this.setState({ error: '' });
            this.context.router.push(json.redirect);
          }
          else {
            this.setState({ error: json.error });
          }
        });

The server sends the cookies just fine, as you can see on chrome’s dev tools: Network - Cookies Network - Headers

But chrome doesn’t set the cookies, in Application -> Cookies -> localhost:8080: “The site has no cookies”.

Using form.submit() while the server sets the cookies and redirects works just fine, the problem only occurs using fetch to retrieve json, so this is why I’m posting it here.

Any idea how to make it work?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:17

github_iconTop GitHub Comments

44reactions
stianlpcommented, Aug 29, 2016

Wow. I just realized I did a major mistake.

So, I have two requests; one login request and one customer request. It is the login request that gets the set-cookie header in its response, and then the user should be loggen in.

There is an option called credentials: ‘same-origin’, which I did not send with the login request (because I thought it only needed to be sent with requests after I was logged in.)

Try this:

fetch('/login/local', {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          credentials: 'same-origin',
          body: JSON.stringify({
            username: this.state.username,
            password: this.state.password,
          }),
        }).then(res => {
          console.log(res.headers.get('set-cookie')); // undefined
          console.log(document.cookie); // nope
          return res.json();
        }).then(json => {
          if (json.success) {
            this.setState({ error: '' });
            this.context.router.push(json.redirect);
          }
          else {
            this.setState({ error: json.error });
          }
        });

Make sure you don’t add the credentials: ‘same-origin’ in the header object. It is not supposed to be there. I’ve seen many do that mistake.

5reactions
GuillaumeCiscocommented, Aug 29, 2017

I had to use credentials: 'include' on the client side and CORS_ALLOW_CREDENTIALS = True in my django app. Also setting my cookie with 127.0.0.1 in localhost response.set_cookie('my_cookie', value=token, httponly=True, domain='127.0.0.1')

Read more comments on GitHub >

github_iconTop Results From Across the Web

Response Cookie not getting set by Chrome & IE
I'm trying to figure out why Chrome (26.0.1410.64) and IE10 don't seem to recognize the cookie I set in my response from an...
Read more >
Set-Cookie - HTTP - MDN Web Docs
The Set-Cookie HTTP response header is used to send a cookie from the server ... to the client the cookie is being set...
Read more >
Cookie not being set in react app (express backend) - Reddit
I have an express back end and I am using express-session to handle my session store. My cookie settings look like this: const...
Read more >
Set-Cookie in response header not stored in the browser, not ...
You cookie has a secure flag set to true and you are trying to access it in a non secure client. · You...
Read more >
Solved: Set-Cookie and Response Body not getting sent toge...
What I've tried: After some tests with AssignMessage, I realized that only the last Set-Cookie was being sent, but when I changed the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found