Flask Session() object not permanent Flask Session() object not permanent flask flask

Flask Session() object not permanent


Found out why sessions wasn't working after a lot of research! Flask sessions are essentially cookies, and I was using the Fetch API to perform CORS operations. Fetch() by default does not allow cookies to be received or sent, and must be configured in order to use Flask sessions.

On my React.js client, I did this by setting 'include' for 'credentials':

        fetch(url, {            method: 'POST',            mode: 'cors',            body: JSON.stringify(loginObj),            credentials: 'include',            headers: {                'Content-Type': 'application/json'            }        })        .then(res => res.json())        ...

Because of this configuration, the request isn't considered a "simple request", and the client will actually "preflight" the POST request with an OPTIONS request. This means that before my POST request is sent, a OPTIONS request testing to see if the server has the correct access will be sent to my Flask server first.

The preflight OPTIONS request will test to see if the response from the server has the correct headers containing "Access-Control-Allow-Origin", 'Access-Control-Allow-Credentials', and 'Access-Control-Allow-Headers'. If the test sent by the OPTIONS request fails, the actual POST request will not be sent and you'll get a Fetch error.

I then set the headers accordingly on my Flask server like so:

@bp.route('/login', methods=('POST','OPTIONS'))def login():    if request.method == 'OPTIONS':        resp = Response()        resp.headers['Access-Control-Allow-Origin'] = clientUrl        resp.headers['Access-Control-Allow-Credentials'] = 'true'        resp.headers['Access-Control-Allow-Headers'] = "Content-Type"        return resp    else:        '''        use session for something          '''          res['actionSuccess'] = False        js = json.dumps(res)        resp = Response(js, status=200, mimetype='application/json')                resp.headers['Access-Control-Allow-Origin'] = clientUrl        resp.headers['Access-Control-Allow-Credentials'] = 'true'        resp.headers['Access-Control-Allow-Headers'] = "Content-Type"        return resp

Take note that 'Access-Control-Allow-Credentials' was set to 'true' as opposed to the Python boolean True, as the client will not recognize the Python boolean.

And with that, a Flask Session object should be stored in your cookies.