Sitemap

How Your Browser Uses Cookies: A Simple Guide to Cookie Management in Flask

4 min readOct 8, 2024

--

Cookies are small pieces of data stored on the client side, which can be used to track user sessions, maintain user preferences, and more. In Flask, cookies can be easily managed using its built-in functionality. In this blog, we’ll dive deep into how cookies work in Flask, how to set, get, and delete them, and we’ll illustrate it with practical examples.

What are Cookies?

Cookies are simple text files sent from a web server to a client browser. They are saved on the client’s computer and contain small pieces of data that are used for various purposes, such as remembering login states, tracking user activities, and maintaining user preferences.

A cookie typically contains:

  • Name: The name of the cookie.
  • Value: The actual data.
  • Domain: The domain for which the cookie is valid.
  • Path: The path in the domain where the cookie is accessible.
  • Expiration: When the cookie expires (optional).
  • Secure/HttpOnly Flags: Additional security flags.

Cookies in Flask

Flask makes it very simple to set, retrieve, and delete cookies. Flask’s Response and request objects handle these operations.

Let’s explore the essential operations for working with cookies in Flask.

Setting a Cookie in Flask

To set a cookie, you can use the set_cookie() method of the Response object. You generally create a response and then attach a cookie to it.

Here’s an example:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/setcookie')
def set_cookie():
# Create a response object
response = make_response("Cookie is set!")

# Set a cookie named 'user' with the value 'Aditya'
response.set_cookie('user', 'Aditya', max_age=60*60*24*7) # Cookie lasts for 7 days

return response

if __name__ == '__main__':
app.run(debug=True)

Explanation:

  • make_response(): This function is used to generate a response to which we can attach cookies or other headers.
  • set_cookie(): It sets the cookie with a name and value. We also set the max_age, which defines the lifespan of the cookie in seconds (here, 7 days).

When the client accesses the /setcookie route, a cookie is set on their browser.

Retrieving a Cookie

Once a cookie is set, you can retrieve it using the request.cookies object. Here’s how you can fetch a cookie:

from flask import Flask, request

app = Flask(__name__)

@app.route('/getcookie')
def get_cookie():
# Retrieve the cookie from the client's request
user_cookie = request.cookies.get('user')

if user_cookie:
return f'The user is {user_cookie}'
else:
return 'No user cookie found!'

if __name__ == '__main__':
app.run(debug=True)

Explanation:

  • request.cookies.get(): This retrieves the cookie with the name 'user'. If the cookie doesn't exist, it returns None.

Deleting a Cookie

To delete a cookie, you simply set the cookie’s expiration date in the past or use delete_cookie() to invalidate it.

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/deletecookie')
def delete_cookie():
response = make_response("Cookie has been deleted!")

# Delete the 'user' cookie
response.delete_cookie('user')

return response

if __name__ == '__main__':
app.run(debug=True)

Explanation:

  • delete_cookie(): This method removes the cookie from the client's browser by invalidating it.

Example: Building a Simple Cookie-Based Login

Let’s build a simple app that simulates login functionality using cookies. When a user logs in, their username will be stored in a cookie, and we’ll display it on subsequent requests.

from flask import Flask, request, make_response, render_template_string, redirect, url_for

app = Flask(__name__)

# Simulating a login page
login_page = '''
<form action="{{ url_for('login') }}" method="POST">
<label for="username">Username:</label>
<input type="text" name="username" id="username">
<button type="submit">Login</button>
</form>
'''

@app.route('/')
def index():
username = request.cookies.get('username')
if username:
return f'Welcome back, {username}!'
else:
return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
response = make_response(redirect(url_for('index')))

# Set cookie with username
response.set_cookie('username', username, max_age=60*60*24*30) # 30 days

return response
return render_template_string(login_page)

@app.route('/logout')
def logout():
response = make_response(redirect(url_for('index')))

# Delete the username cookie
response.delete_cookie('username')

return response

if __name__ == '__main__':
app.run(debug=True)

Explanation:

  1. Index Page: If a user visits the site and has a cookie with the username, we greet them. Otherwise, they are redirected to the login page.
  2. Login Page: When a user logs in by submitting a username, we store it in a cookie.
  3. Logout: Deletes the username cookie and redirects the user back to the index.

Running the Application:

  1. Go to / — if there is no cookie, you’ll be redirected to the login page.
  2. Log in with a username. The username will be stored in a cookie.
  3. Visit / again — now you’ll be greeted by your username.
  4. Log out via /logout — this will delete the cookie.

Securing Cookies in Flask

To make cookies more secure, you can use the HttpOnly and Secure flags. These flags prevent cookies from being accessed by client-side scripts and ensure cookies are sent over HTTPS connections only.

response.set_cookie('username', 'Aditya', max_age=60*60*24*7, httponly=True, secure=True)
  • httponly=True: Prevents JavaScript from accessing the cookie.
  • secure=True: Ensures the cookie is sent over secure HTTPS connections.

Conclusion

Cookies are a powerful way to manage state and user preferences in Flask. In this blog, we’ve explored how to set, retrieve, and delete cookies using practical examples. Cookies can also be secured using flags to prevent malicious access. With this understanding, you can now integrate cookies into your Flask applications to manage user sessions, preferences, and more.

--

--

Aditya Mangal
Aditya Mangal

Written by Aditya Mangal

Tech enthusiast weaving stories of code and life. Writing about innovation, reflection, and the timeless dance between mind and heart.

No responses yet