Flask Session: How to Store and Manage User Data

Video thumbnail

When we develop a web application with Flask, the time comes when we need to maintain user information between requests: who logged in, what's in their shopping cart, or what preferences they chose, and not just temporary messages that last one request, like flash messages in Flask

That's where the Flask Session comes into play, a lightweight and very useful tool for managing temporary data on the server side (or client side, depending on the configuration).

The use of the session in any web system is used to store information related to a user; data such as name, identifier, that is, of an authenticated user, are saved in it, as we will see in the next section; for now, we don't have a use for it, so we will continue using the session in later chapters and we will see some examples of its use.

Another common example of session usage is for shopping carts, to record each of the products that are going to be purchased.

The data stored in the session is temporary data, as the session will eventually expire.

The session is usually modified, meaning adding, updating, and deleting references as requests are made to the server, for example, when a user is going to authenticate after a successful login, the authenticated user's data is registered in the session; when they are going to log out, this data is destroyed; if you have a shopping cart, when making the purchase, all this data is removed from the session.

What is a Session in Flask and what is it for

A session is a temporary storage space that saves information between different HTTP requests. In Flask, each user has their own session, identified by a secure cookie.

For example, when a user logs in successfully, their name or ID can be saved within the session to recognize them on each visit. In my case, I usually use it precisely for that: to store the authenticated user's data without having to request it again on every page.

To use the session, a secret key must be set, which is established from the beginning of the project in the configuration file:

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

Differences between Session and Cookies

Although both allow information to be saved between requests, there are key differences:

Aspect    Cookie    Session
Data Location    User's browser    Server (or encrypted in a signed cookie)
Security    Lower    Higher (signing and encryption)
Duration    According to configuration    Expires automatically or manually

⚙️ Configuring the Session in a Flask project

Before using the session, we need to configure a secret key that Flask uses to sign the cookies and prevent manipulation.

You can do this directly in your main file or in a custom configuration in Flask:

from flask import Flask
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

To use the session, we must import the object called session that is part of the framework:

from flask import session

With this, we can set data in the session as if it were an array:

session['username'] = 'user'

And get this data using:

session['username']

Or remove the data:

session.pop('username', None)

You can see a complete example, implementing the following controllers in a test file:

from flask import session
***
@app.route('/test/session/check')
def test_session_check():
    if 'username' in session:
        return 'Logged in as '+session["username"]
    return 'You are not logged in'

@app.route('/test/session/set')
def test_session_set():
    session['username'] = 'user'
    return 'Test'

@app.route('/test/session/pop')
def test_session_pop():
    session.pop('username', None)
    return 'Test'

And evaluate the result.

Practical examples of session usage

Let's look at a small test module with three routes to test the session in action:

from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'clave_super_secreta'
@app.route('/test/session/set')
def test_session_set():
   session['username'] = 'user'
   return 'Sesión creada para user'
@app.route('/test/session/check')
def test_session_check():
   if 'username' in session:
       return f'Usuario autenticado: {session["username"]}'
   return 'No hay sesión activa'
@app.route('/test/session/pop')
def test_session_pop():
   session.pop('username', None)
   return 'Sesión eliminada'

Maintaining user data after login

When a user logs in, it's enough to assign their data to session. This allows them to be identified anywhere in the application as long as their session is active.

️ Implementing a shopping cart

In another project, I used the session to save a list of products like this:

session['cart'] = ['Book A', 'Book B']

And upon completing the purchase, it was enough to clear the data:

session.pop('cart', None)

Flask-Session Extension: Server-side sessions

By default, Flask saves the session in a signed client-side cookie. But if you need greater persistence or storage in memory/Redis, you can use the Flask-Session extension.

Installation and Configuration

$ pip install Flask-Session

from flask_session import Session

app.config['SESSION_TYPE'] = 'filesystem'
Session(app)

Usage with Redis and other storage options

You can also use SESSION_TYPE = 'redis' to store sessions on a Redis server, ideal for distributed or large-scale applications.

Best practices and security

️ Avoiding exposure of sensitive data

Never save passwords, tokens, or private information directly in the session. Use anonymous or encrypted identifiers.

⏱️ Controlling session expiration

Configure the expiration time with:

app.permanent_session_lifetime = timedelta(minutes=30)

Configuring secure cookies (SESSION_COOKIE_SECURE)

Make sure to use HTTPS and mark cookies as secure:

app.config['SESSION_COOKIE_SECURE'] = True

How to add more than one element to session in Flask using arrays

In Flask, the session is a way of storing data that is associated with a user during the use of the application, usually the use of the session is related to an authenticated user, but the user can also use the session without having to be authenticated. For example, if a user logs into a Flask web application, a session can be created to manage the basic data of this user, such as her name, email and indentifier, among other preferences.

Flask provides an easy way to work with the session through the session object, which is a Python object that is stored in cookies in the user's browser.

To use the session in Flask you can use functions like session.get() and session.pop() to read and write data to the session, respectively.

The use of the session is very simple in Flask and we will see how we can save more than just text, numbers or the like:

session['age'] = 30
session['name'] = "Andres"

First of all, remember that we can import it internally from Flask:

from flask import session

And we define a couple of functions, to add and remove elements from an array, in this case:

def addRoomSession(room):
    if 'rooms' not in session:
        session['rooms'] = []
    
    rooms = session['rooms']
    rooms.append(room)
    session['rooms'] = rooms
    print(session['rooms'])
def removeRoomSession(room):
    if 'rooms' not in session:
        return
    
    rooms = session['rooms']
    rooms.remove(room)
    session['rooms'] = rooms

The idea is to notice that we can store arrays inside the session:

rooms = session['rooms'] # get the session, the key we want to modify
rooms.append(room) # we add our elements
session['rooms'] = rooms # set it back to the session

This code is part of my complete course on Flask, in which we see how to work with Flask Socket IO and rooms.

Conclusion

The Flask Session is an essential tool for maintaining user data between requests, without complicating the backend.
In my experience, its combination of simplicity and security makes it perfect for managing login, shopping carts, or any flow that requires temporary persistence.
If your project grows, you can expand its capacity with Flask-Session and Redis, ensuring scalability and total data control.

❓ Frequently Asked Questions (FAQ)

What happens if the server restarts?
Cookie sessions are maintained as long as the secret key doesn't change; server sessions may be lost if you don't use persistent storage.

Can I save complex objects?
Yes, but they must be serializable (JSON, for example).

How do I delete all session data?
You can use session.clear() to clean up completely.

Is Flask Session secure?
Yes, as long as you use a robust secret key and secure cookies under HTTPS.

I agree to receive announcements of interest about this Blog.

The use of the session in any web system is used to store information related to a user, in which data such as the name and identifier are stored. We will see how to use it in Flask.

| 👤 Andrés Cruz

🇪🇸 En español