3

i'm building a website in nodejs with expressjs and i'm using express-sessions for handling the users sessions. here is my code.

on app.js file from where the app starts.

app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());

app.use(session(config.sessionConfig));

app.use(override());

the config.sessionConfig object is here

  sessionConfig : {
    secret: 'shhSecrt',
    store: new MongoStore({ url:dbUrl+dbName}),
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
  }

The problem is that when i deploy it to heroku the req.session variable doesnt seem to mantain its state. To be more specificaly, when a user registers i store for example his username in the req.session.usernname variable but on the next request that the user does the req.session.username is undefined not because that is not stored on the db, but because the server can not recognize his session! I dont know why, I have being trying to solve it for 2 days and i cant figure out. Also when i run the app in localhost everything works fine. Please Help!! thank you!

*let me know if you need more info or code sample.

user2487076
  • 73
  • 5
  • 10

2 Answers2

1

I was running into a similar issue and the following was the fix I needed. Perhaps yours is similar:

https://github.com/expressjs/session/issues/633

The solution references a key piece of information from the documentation: enter image description here

Setting the trust proxy to high and securing the cookie allowed the cookie to persist for me on Heroku.

SethGoodluck
  • 380
  • 3
  • 14
1

I was also facing the same problem and thought that maybe it's a bug... but i found that setting up the session like below

app.set('trust proxy', 1)
app.use(session({
  resave: false,
  saveUninitialized: true,
  secret: 'your secret text',
  cookie: {
    secure: (process.env.NODE_ENV && process.env.NODE_ENV == 'production') ? true:false
  }
}))

fixes the problem :D