Mit
Mit

Reputation: 349

How to read cookies on server-side with Express?

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?

Upvotes: 0

Views: 1469

Answers (1)

Patrick Hund
Patrick Hund

Reputation: 20236

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

Upvotes: 1

Related Questions