Flask’s default session stores all your data in a cookie — the more items in the cart, the bigger the cookie gets, and anyone can read its contents because the cookie is only signed, not encrypted. Flask-Session moves session data to the server (Redis); the browser only keeps a short session id. This post shows how to set up Flask-Session 0.8.0 with Redis in 5 minutes — the code that uses session doesn’t change a line.
The Problem: The Default Session Lives Entirely in a Cookie
When you assign session['cart'] = [...], Flask serializes the data to JSON, signs it with SECRET_KEY, and puts it in the session cookie sent with every request. Convenient at first, but with three annoying consequences. First, browsers cap each cookie at roughly 4KB — a cart with many items blows past the limit and the session mysteriously “disappears”. Second, the data is only signed, not encrypted: anyone can base64-decode it and read the cart or any sensitive data that ended up in the session. Third, every request carries the whole session along. Measured on Flask 3.1.3: a 51-item cart made the cookie 1,294 characters long.
from flask import Flask, sessionapp = Flask(__name__)app.config["SECRET_KEY"] = "doi-thanh-bien-moi-truong"@app.route("/cart/add/<int:product_id>")def add_to_cart(product_id): cart = session.get("cart", []) cart.append(product_id) session["cart"] = cart return {"cart": cart}
The Solution: Move Sessions to Redis with Flask-Session
Install two packages, add a few lines of config — the code that uses session stays the same. Flask-Session replaces the default session interface with RedisSessionInterface: data lives in Redis under the key session:<id>, and the browser cookie holds only the session id.
pip install flask-session redis
from datetime import timedeltafrom flask import Flask, sessionfrom flask_session import Sessionfrom redis import Redisapp = Flask(__name__)app.config["SECRET_KEY"] = "doi-thanh-bien-moi-truong"app.config["SESSION_TYPE"] = "redis"app.config["SESSION_REDIS"] = Redis.from_url("redis://127.0.0.1:6379")app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=7)Session(app)@app.route("/cart/add/<int:product_id>")def add_to_cart(product_id): cart = session.get("cart", []) cart.append(product_id) session["cart"] = cart return {"cart": cart}@app.route("/cart")def view_cart(): return {"cart": session.get("cart", [])}@app.route("/logout")def logout(): session.clear() return "Da dang xuat"
Measured again with the same cart: the cookie is only 108 characters, because it carries just the session id. Redis deletes expired keys automatically thanks to the TTL from PERMANENT_SESSION_LIFETIME (31 days by default; the example above shortens it to 7). Note: session data must be serializable (msgpack is the default format since Flask-Session 0.7.0 and only accepts simple types like dict, list, str, and numbers); if you don’t have Redis on your dev machine yet, use the cachelib backend with FileSystemCache temporarily and switch to Redis when you deploy.
Apply It to Your Project
Switch to Flask-Session when the session holds a cart, a multi-step form, or temporary data larger than a few hundred bytes — that’s when the default cookie is about to hit its limit. It’s also the right call when you need to revoke sessions from the server: logging out of every device is just deleting the session:<id> key in Redis, instead of waiting for the cookie to expire. On logout, remember to call session.clear() to delete the data in Redis too. Finally, lock Redis down: bind localhost only, set a password, and don’t expose port 6379 to the internet.
Related Posts
- Flask: Lock Down Session Cookies with a Strong SECRET_KEY, Secure and SameSite in 5 Minutes
- Flask: Managing Login with Flask-Login — login_required and Remember Me in 5 Minutes
- Flask: tăng tốc API bằng cache với Flask-Caching trong 5 phút
FAQ
Does Flask-Session change how I use session?
No. You still use flask.session exactly as before — set, read, and delete the same way, because Flask-Session only changes where the data is stored underneath.
What if I don’t have Redis?
Use the cachelib backend with FileSystemCache for now; just change SESSION_TYPE to 'cachelib'. In production use Redis or Memcached; the SQLAlchemy backend works too, but you have to clean up expired sessions yourself with the flask session_cleanup command.
Is a session stored in Redis safer than a cookie?
Yes: the data is no longer in the user’s hands, so it can’t be read or tampered with. But you must protect Redis: bind localhost, set a password, and don’t expose port 6379. SECRET_KEY still needs to be strong, because anyone who guesses a session id can take over that session.
When does a session expire?
After 31 days by default, per PERMANENT_SESSION_LIFETIME. Redis deletes expired keys automatically thanks to the TTL, so no manual cleanup is needed. With SESSION_PERMANENT=False the cookie is deleted when the browser closes, but the data on the server still lives until the TTL ends — keep the default True.
💬 Have you tried this in your own project? If you hit an error or have a shorter way, leave a comment below — I read them all and will fold the good ideas into the post.
