Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs - heroku - express-sessions

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.

like image 798
user2487076 Avatar asked Dec 08 '25 17:12

user2487076


1 Answers

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.

like image 87
SethGoodluck Avatar answered Dec 10 '25 12:12

SethGoodluck