Flask

Flask Session Tutorial: How to Manage User Sessions in Flask


Managing user sessions is an essential part of web development — it allows your Flask application to remember information about users across multiple requests. In this tutorial, you'll learn how to set, get, and remove session data in Flask using the built-in session object.


What is a Session in Flask?

A session is a way to store data that is specific to a user across different requests. Unlike cookies, the session data is stored on the server (and only a session ID is stored in the user's browser). Flask makes this easy through the flask.session object.


1. Basic Setup

Before you start working with sessions, you must set a SECRET_KEY for your Flask app. This key is used to securely sign session cookies.

from flask import Flask, session, render_template, request, redirect, url_for

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'

2. Setting Session Values

You can assign values to the session object just like a dictionary. For example, you can store a username after a successful login.

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form.get('username')
        return redirect(url_for('profile'))
    return render_template('login.html')

When a user logs in, their username is stored in the session and can be accessed later.


3. Accessing Session Values

To retrieve session data, simply use the same key. If the key doesn't exist, redirect the user to the login page.

@app.route('/profile')
def profile():
    if 'username' not in session:
        return redirect(url_for('login'))
    return render_template('profile.html', username=session['username'])

4. Removing Session Values

When the user logs out, remove their session data using session.pop().

@app.route('/logout')
def logout():
    session.pop('username', None)
    return render_template('logout.html')

This clears the stored username and ends the session for that user.


Final Thoughts

Flask's session management is simple yet powerful. You can store small bits of user information securely between requests — perfect for login systems, user preferences, or temporary data.

If you need more security or scalability, consider integrating server-side session storage (e.g., Redis or Flask-Session extension).