Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sessions always empty with flask / heroku

I'm having an issue with my application on Heroku where sessions aren't persisting. Specifically, flask's SecureCookieSession object is empty, every time a request is made. Contrast this with running my application on localhost, where the contents of SecureCookieSession persist the way they should.

Also I'm using flask-login + flask-seasurf, but I'm pretty sure the issue happening somewhere between flask / gunicorn / heroku.

Here are three questions that describe a similar issue:

  1. Flask sessions not persisting on heroku
  2. Flask session not persisting
  3. Flask-Login and Heroku issues

Except I'm not dealing with AJAX or multiple workers here (it's a single heroku free dyno, with a single line in the Procfile). I do get the feeling that using server side sessions with redis or switching from Heroku to something like EC2 might solve my problem though.

Also, here's my git repo if it helps https://gitlab.com/collectqt/quirell/tree/develop. And I'm testing session stuff with

def _before_request(self):
    LOG.debug('SESSION REQUEST '+str(flask.session))

def _after_request(self, response):
    LOG.debug('SESSION RESPONSE '+str(flask.session))
    return response
like image 284
lynn Avatar asked Jan 31 '26 23:01

lynn


2 Answers

Got the solved with some external help, mainly by changing the secret key to use a random string I came up with, instead of os.urandom(24)

Changing to server side redis sessions helped too, if only by making testing simpler

like image 68
lynn Avatar answered Feb 03 '26 12:02

lynn


Just in case someone else comes across this question, check APPLICATION_ROOT configuration variable. I recently deployed a Flask application to a subdirectory under nginx with a reverse-proxy and setting the APPLICATION_ROOT variable broke Flask's session. Cookies aren't being set under the correct path because of that.

like image 27
lukecampbell Avatar answered Feb 03 '26 14:02

lukecampbell