Python Docs

Sessions & Cookies

Web applications are stateless, meaning each request is independent. Cookies and Sessions help maintain state (like logged-in user info) across requests.

Cookies (Client-Side)

Cookies are small values stored in the user's browser. They are sent with every request and are ideal for:

  • Saving user preferences
  • Tracking sessions
  • Lightweight authentication tokens
  • Identifying returning users

Example: Cookies in Flask

from flask import Flask, make_response, request
app = Flask(__name__)

@app.get('/set-cookie')
def set_cookie():
    resp = make_response('Cookie set')
    resp.set_cookie('username', 'alice', max_age=3600)
    return resp

@app.get('/get-cookie')
def get_cookie():
    username = request.cookies.get('username')
    return f'Username: {username}'

Key points:

  • set_cookie() stores data in browser.
  • max_age controls expiration.
  • request.cookies retrieves cookies from client.

Sessions (Server-Side)

Sessions store user data on the server, identified by a session cookie. Suitable for:

  • Login state (user_id)
  • Shopping cart items
  • Dashboard preferences
  • Temporary authentication tokens

Example: Sessions in Flask

from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'dev-secret-key'  # Change in production

@app.get('/login')
def login():
    session['user_id'] = 123
    return 'Logged in'

@app.get('/profile')
def profile():
    user_id = session.get('user_id')
    if not user_id:
        return 'Not logged in', 401
    return f'User {user_id}'

@app.get('/logout')
def logout():
    session.pop('user_id', None)
    return 'Logged out'

Key session concepts:

  • session behaves like a Python dictionary.
  • session['user_id'] stores state on server.
  • session.get() safely retrieves values.
  • logout removes data from session with session.pop().

Security Tips

To protect sessions and cookies, always:

  • Use secure=True so cookies are sent only over HTTPS.
  • Use httponly=True to prevent JavaScript theft (XSS protection).
  • Set samesite='Strict' to prevent CSRF attacks.
  • Keep short expiry for sensitive cookies (sessions, tokens).
  • Store SECRET_KEY in environment variables (never in code).
  • Regenerate session IDs after login to prevent fixation attacks.

Summary

Cookies store data on the client, while sessions securely store data on the server. Both are essential for authentication, state management, personalization, and secure user experiences in web applications.