0

On my client-side I'am saving a token in the user's cookies :

this.socket.on('server:authentication', function(tokenObject){
  if(tokenObject){
    sessionStorage.setItem("token", tokenObject);
    this.setState({ submitted: true});
  }
}.bind(this));

Then I want to read that token on the server side, but when I do :

app.use(cookieParser());

app.use(function(req, res, next){
    const { token } = req.cookies;
    console.log(token);
...
});

I get "undefined" on the console. Same thing when I try console.log(req.cookies.token). How can I achieve that?

Mit
  • 339
  • 1
  • 7
  • 23
  • Are you attaching the desired cookies to the HTTP request? When you call `req.cookies` you are checking the cookies attached to that request. Just because the cookies have been set on the client side does not mean that they are automatically attached to your HTTP requests. – AJ Funk May 18 '17 at 15:01
  • No I'm not attaching the cookies I tought It was automatically made. How can I make the client-side send his cookies? – Mit May 18 '17 at 15:03
  • It depends on what you are using to make the request, but I'm guessing you may need to set `withCredentials` to true. For example, [here's how to do it with jQuery](http://stackoverflow.com/questions/10230341/http-cookies-and-ajax-requests-over-https/10249123) – AJ Funk May 18 '17 at 15:36

1 Answers1

1

You need to set the cookie in your client-side code, you're currently setting is in sessionStorage, which is a different beast.

this.socket.on('server:authentication', function(tokenObject){
    if(tokenObject){
        document.cookie = 'token=' + tokenObject;
        sessionStorage.setItem("token", tokenObject);
        this.setState({ submitted: true});
    }
}.bind(this));

See How to set cookie and get cookie with JavaScript

Community
  • 1
  • 1
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95