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.

New session on every request

See original GitHub issue

I’ve setup cookie-session exactly according to the instructions to test its work. But I get new session on every request: Here’s the initialization code:

app.use(cookieSession({
    name: 'session',
    keys: [Constants.COOKIE_SESSION_KEY_1, Constants.COOKIE_SESSION_KEY_2]
}));
app.use(function (req, res, next) {
    req.sessionOptions.maxAge = 60000;
    next();
})

And here’s the testing one:

router.get('/auth', function(req, res, next) {

    console.log("SESSION BEFORE:", JSON.stringify( req.session), req.session.isNew);
    res.json({ok: 'ok'})
    req.session.test = 1;
    console.log("SESSION AFTER:", JSON.stringify(req.session));
}

It always gives me this output:

SESSION BEFORE: {} true SESSION AFTER: {“test”:1}

I’m doing fetch() requests with credentials: ‘include’ option. I used client-sessions module before and it could set cookie

Am I missing anything?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
dougwilsoncommented, Jul 3, 2017

Hi @caseyryan weird, if I run only the code you provided above, where I just made my login function setTimeout internally and then setup the most minimal Express around that route you gave as the only route, setting the session inside the callback did work fine. This means that the issue is somewhere between the minimal case I created and your full app. Since I can’t see any other code than what you posted above, I’m not sure what the difference is. Here is the app I made:

var express = require('express');
var cookieSession = require('cookie-session');

var app = express();
app.use(cookieSession({
  name: 'session',
  keys: ['foo', 'bar']
}));

app.get('/auth', function(req, res, next) {
  console.log("SESSION BEFORE:", JSON.stringify( req.session), req.session.isNew);
  var params      = req.query;
  var act         = params.act;

  switch (act) {
    case 'check':
      console.log('SESSION CHECK >>> ', JSON.stringify(req.session));
      res.end();
      break;
    case 'login':
      var code        = params.code;
      var state       = params.state;
      login(code, state, function(result) {
        if (result) {
          if (result.accessToken) {
            console.log("WRITING SESSION BEFORE: ", JSON.stringify(req.session), req.session.isNew);
            req.session.accessToken = result.accessToken;
            req.session.userId      = result.userId;
            req.session.firstName   = result.firstName;
            req.session.lastName    = result.lastName;
            req.session.photoURL    = result.photoURL;
            console.log("SESSION IS SET: " + JSON.stringify(req.session), req.session.isNew);
            res.end(); 
          } else {
            req.session = null;
            res.end();
          }
        } else {
            req.session = null;
            res.end();
        }
      });
      break;
    case 'logout':
      req.session = null;
      res.end();
      break;
  }
});

app.listen(3000);

function login(code, state, cb) {
  setTimeout(function () {
    cb({
      accessToken: 'token',
      userId: 42,
      firstName: 'john',
      lastName: 'doe',
      photoURL: null
    });
  }, 2000)
}

And here is me trying to run it, getting the session cookie even with the async login call and the check validating it:

$ npm i express cookie-session
npm WARN saveError ENOENT: no such file or directory, open '/Users/doug.wilson/Code/cookie-session-83/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/Users/doug.wilson/Code/cookie-session-83/package.json'
npm WARN cookie-session-83 No description
npm WARN cookie-session-83 No repository field.
npm WARN cookie-session-83 No README data
npm WARN cookie-session-83 No license field.

+ cookie-session@2.0.0-beta.2
+ express@4.15.3
added 50 packages in 2.926s

$ node app &
[1] 72517

$ curl -i http://127.0.0.1:3000/auth?act=login
SESSION BEFORE: {} true
WRITING SESSION BEFORE:  {} true
SESSION IS SET: {"accessToken":"token","userId":42,"firstName":"john","lastName":"doe","photoURL":null} true
HTTP/1.1 200 OK
X-Powered-By: Express
Set-Cookie: session=eyJhY2Nlc3NUb2tlbiI6InRva2VuIiwidXNlcklkIjo0MiwiZmlyc3ROYW1lIjoiam9obiIsImxhc3ROYW1lIjoiZG9lIiwicGhvdG9VUkwiOm51bGx9; path=/; httponly
Set-Cookie: session.sig=hiVuIyqScdW5vUbQQnqYidPfStU; path=/; httponly
Date: Mon, 03 Jul 2017 14:26:38 GMT
Connection: keep-alive
Content-Length: 0

$ curl -i -H'Cookie: session=eyJhY2Nlc3NUb2tlbiI6InRva2VuIiwidXNlcklkIjo0MiwiZmlyc3ROYW1lIjoiam9obiIsImxhc3ROYW1lIjoiZG9lIiwicGhvdG9VUkwiOm51bGx9; session.sig=hiVuIyqScdW5vUbQQnqYidPfStU' http://127.0.0.1:3000/auth?act=check
SESSION BEFORE: {"accessToken":"token","userId":42,"firstName":"john","lastName":"doe","photoURL":null} false
SESSION CHECK >>>  {"accessToken":"token","userId":42,"firstName":"john","lastName":"doe","photoURL":null}
HTTP/1.1 200 OK
X-Powered-By: Express
Date: Mon, 03 Jul 2017 14:27:19 GMT
Connection: keep-alive
Content-Length: 0
0reactions
caseyryancommented, Jul 3, 2017

Ok, to be exact, I’ve made authorization for 2 Russian social networks vk.com and ok.ru. They both have standard OAuth2 authentication process for websites and third party applications which described here . My setup islike this: React-Redux frontend and Express backend api server. React is running on localhost:3000 and express is on localhost:3001. React proxies all requests to express. But as social network redirects a browser to ‘redirect_uri’ which I specify in my request to it and puts code and state params directly to the url, I can’t do it via proxy, so I’m doing this: window.location.href = getLoginURL(); It forms the proper request URL to social network so that it could return code and state to my app which I can use for getting access_token from my server. And the problem starts exactly after I do this action. The SN responds with code and state params and also sets it’s own headers. After this I can’t set my own session until I reload the whole page and do my first fetch() request to my API server. If the first request would be to my API server instead of VK, Odnoklassniki or Twitter, the sessions will work like a charm

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js - Express-session creates new session every request
I put my node express server into production. In development, express-session worked fine (it stored session into ...
Read more >
Express creating new session for each request #330 - GitHub
Express-session is creating a new session (new sessionID) for new request. And it happens intermittently, for example sometimes for first ...
Read more >
Laravel 5 creates a new session after each request - Laracasts
Hello I am working with the development version of Laravel 5 and I have a problem. If I try this: Session::set('hi', 'hello') dd(Session::get('hi'))...
Read more >
Cookie problem in IIS7 and IE: New session id with ... - MSDN
Hi, I have a website running in IIS7 and it seems to be creating a new session for every request I make. The...
Read more >
Cookie and Session (II): How session works in express-session
Session is created in server when the client send a request to it for the first time. There are different ways to create...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

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