Last Updated : 23 Jul, 2025
Sessions in Flask store user-specific data across requests, like login status, using cookies. Data is stored on the client side but signed with a secret key to ensure security. They help maintain user sessions without requiring constant authentication.
This article demonstrates how to implement server-side sessions in Flask using the Flask-Session extension. We’ll create a simple app that remembers a user’s name between requests, enabling login and logout functionality.
InstallationTo learn how to create and set-up flask app, refer to- Create Flask App
After creating a Flask app, we need to install modules required in this project, to install them execute this command in the terminal-
File Structurepip install flask flask-session
In the end, our file structure of the app should look similar to this
File Structure Importing Modules and Configuring Flask-SessionIn this section, we import the necessary modules and configure the Flask app to use server-side sessions. The configuration sets the session type (filesystem) and defines whether sessions are permanent.
Python
from flask import Flask, render_template, redirect, request, session
from flask_session import Session
app = Flask(__name__)
# Configuration
app.config["SESSION_PERMANENT"] = False # Sessions expire when the browser is closed
app.config["SESSION_TYPE"] = "filesystem" # Store session data in files
# Initialize Flask-Session
Session(app)
Explanation:
Now we define the routes for the app that will handle the session. This application includes three routes- home route, login route and logout route:
Python
@app.route("/")
def index():
# If no username in session, redirect to login
if not session.get("name"):
return redirect("/login")
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# Record the user name in session
session["name"] = request.form.get("name")
return redirect("/")
return render_template("login.html")
@app.route("/logout")
def logout():
# Clear the username from session
session["name"] = None
return redirect("/")
Explanation:
Create the following html files in the templates folder:
layout.htmlProvides a basic HTML structure and a block for inserting page-specific content.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="initial-scale=1, width=device-width">
<title>Flask Session Demo</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
login.html
Contains a simple form to input a username. It extends layout.html.
HTML
{% extends "layout.html" %}
{% block content %}
<h1>Register</h1>
<form action="/login" method="POST">
<input placeholder="Name" autocomplete="off" type="text" name="name" required>
<input type="submit" value="Register">
</form>
{% endblock %}
index.html
Displays the current session's username (if available) and a logout link.
HTML
{% extends "layout.html" %}
{% block content %}
{% if session.name %}
You are registered as {{ session.name }}. <a href="/logout">Logout</a>.
{% else %}
You are not registered. <a href="/login">Login</a>.
{% endif %}
{% endblock %}
Complete app.py Code
Below is the complete code for app.py:
Python
from flask import Flask, render_template, redirect, request, session
from flask_session import Session
app = Flask(__name__)
# ---------------- Configuration ----------------
app.config["SESSION_PERMANENT"] = False # Sessions expire when browser closes
app.config["SESSION_TYPE"] = "filesystem" # Store session data on the filesystem
Session(app)
# ---------------- Routes ----------------
@app.route("/")
def index():
if not session.get("name"):
return redirect("/login")
return render_template("index.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
session["name"] = request.form.get("name")
return redirect("/")
return render_template("login.html")
@app.route("/logout")
def logout():
session["name"] = None
return redirect("/")
if __name__ == "__main__":
app.run(debug=True)
When using Flask-Session with a filesystem backend, session data is stored on the server instead of in the browser. However, a session cookie (usually named session) is still sent to identify your session.
Let's see how we can view our session.
How to Check the SessionStep 1: First start the application using this command in terminal-
python app.py
Step 2: Register by entering a username to create a session, below is the snapshot of the live app
login.html
index.html
Step 3: After running the app and creatng a session, perform these steps-
Below is the snapshot of a session.
SessionRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4