0
0
Flaskframework~15 mins

Setting and reading cookies in Flask - Deep Dive

Choose your learning style9 modes available
Overview - Setting and reading cookies
What is it?
Cookies are small pieces of data stored by a web browser that help websites remember information about you. In Flask, you can set cookies to save data on the user's browser and read them later when the user visits again. This helps create a smoother and more personalized experience. Cookies are sent back and forth between the browser and server with each request and response.
Why it matters
Without cookies, websites would forget who you are every time you visit, making you log in repeatedly or lose your preferences. Cookies solve this by storing small bits of data on your device, allowing websites to recognize you and keep track of your session or settings. This makes web apps feel more friendly and useful.
Where it fits
Before learning cookies, you should understand how HTTP requests and responses work in Flask. After cookies, you can learn about sessions, which build on cookies to manage user login states more securely.
Mental Model
Core Idea
Cookies are like tiny notes your browser keeps for a website to remember you between visits.
Think of it like...
Imagine visiting a coffee shop where the barista writes your favorite drink on a sticky note and sticks it on your cup. Next time you come, they see the note and make your drink without asking. Cookies work similarly by storing small notes in your browser for websites.
┌───────────────┐       ┌───────────────┐
│   Browser     │       │    Server     │
│               │       │               │
│  Stores cookie│◄──────│  Sets cookie  │
│  Sends cookie │──────►│  Reads cookie │
└───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat are cookies in web apps
🤔
Concept: Cookies store small data on the user's browser to remember information between visits.
Cookies are pieces of text data that websites ask your browser to save. Each time you visit, your browser sends these cookies back to the website. This helps the website remember things like your language choice or login status.
Result
You understand that cookies are small data stored on your device by websites to keep track of information.
Understanding cookies as stored notes in the browser is the base for all web personalization and session management.
2
FoundationHow Flask handles HTTP requests and responses
🤔
Concept: Flask uses request and response objects to communicate with the browser, which is where cookies live.
When a user visits a Flask app, Flask creates a request object with data from the browser, including any cookies sent. Flask then sends back a response object, which can include new cookies to store. Cookies travel inside HTTP headers.
Result
You see that cookies are part of the HTTP headers in requests and responses in Flask.
Knowing that cookies are part of HTTP headers helps you understand how to read and set them in Flask's request and response objects.
3
IntermediateSetting cookies in Flask responses
🤔Before reading on: Do you think setting a cookie requires modifying the request or the response object? Commit to your answer.
Concept: Cookies are set by adding them to the response object before sending it to the browser.
In Flask, you create a response (like with make_response) and then use response.set_cookie(key, value) to add a cookie. When the browser receives this response, it saves the cookie for future requests.
Result
The browser stores the cookie you set and sends it back on later visits.
Understanding that cookies are set on the response clarifies why you can't set cookies just by reading the request.
4
IntermediateReading cookies from Flask requests
🤔Before reading on: Do you think cookies are stored in the response or request object when a user visits? Commit to your answer.
Concept: Cookies sent by the browser are available in the Flask request object under request.cookies.
When a user visits, Flask's request.cookies dictionary contains all cookies sent by the browser. You can access a cookie by its name, for example, request.cookies.get('username').
Result
You can retrieve stored cookie values sent by the browser in your Flask route handlers.
Knowing that cookies come from the request helps you understand how to personalize responses based on stored data.
5
IntermediateCookie attributes and security options
🤔Before reading on: Do you think cookies are always accessible by JavaScript or only by the server? Commit to your answer.
Concept: Cookies have attributes like expiration, path, HttpOnly, and Secure that control their behavior and security.
When setting cookies in Flask, you can specify options like max_age (how long it lasts), path (which URLs send it), HttpOnly (prevents JavaScript access), and Secure (only sent over HTTPS). These control how and when cookies are sent and protect user data.
Result
You can create cookies that expire, are limited to certain paths, or are protected from JavaScript to improve security.
Understanding cookie attributes helps you write safer web apps and avoid common security risks like cross-site scripting.
6
AdvancedDeleting and updating cookies in Flask
🤔Before reading on: Do you think deleting a cookie means removing it from the request or instructing the browser to remove it? Commit to your answer.
Concept: To delete a cookie, you send a response that tells the browser to remove it by setting its expiration in the past.
Flask's response.delete_cookie(key) method sends a cookie with the same name but an expired date, instructing the browser to remove it. Updating a cookie is done by setting it again with a new value.
Result
You can control cookie lifecycle by deleting or updating cookies through responses.
Knowing that cookie deletion is a message to the browser, not immediate removal, prevents confusion about cookie state.
7
ExpertCookie size limits and performance impact
🤔Before reading on: Do you think cookies can store unlimited data or have size limits? Commit to your answer.
Concept: Cookies have size limits (usually around 4KB) and are sent with every request, so large cookies can slow down your app.
Browsers limit cookie size per cookie and total cookies per domain. Sending large cookies wastes bandwidth and slows page loads. Experts keep cookies small and use other storage (like server sessions or localStorage) for bigger data.
Result
You avoid performance problems by managing cookie size and choosing the right storage method.
Understanding cookie size limits and their impact on network traffic is key to building fast, scalable web apps.
Under the Hood
Cookies are stored as key-value pairs in the browser and sent in HTTP headers named 'Cookie' with each request. When the server wants to set or change a cookie, it sends a 'Set-Cookie' header in the HTTP response. The browser then saves or updates the cookie accordingly. Cookies include metadata like expiration and security flags that the browser enforces. Flask accesses these headers through its request and response objects, abstracting the raw HTTP details.
Why designed this way?
HTTP is stateless, meaning each request is independent. Cookies were designed to add state by letting servers store small data on the client side. Using headers keeps cookies compatible with the HTTP protocol without changing it. This design balances simplicity, backward compatibility, and flexibility. Alternatives like URL parameters were less secure and messy, so cookies became the standard.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Browser     │       │    Network    │       │    Server     │
│               │       │               │       │               │
│ Stores cookie │       │               │       │ Reads cookie  │
│ Sends cookie  │──────▶│ HTTP Request  │──────▶│               │
│               │       │ (Cookie header)│       │               │
│               │       │               │       │ Sets cookie   │
│               │       │               │       │ (Set-Cookie)  │
│               │       │               │       │               │
│               │       │               │       │ Sends response│
│               │◀──────│ HTTP Response │◀──────│               │
│               │       │ (Set-Cookie)  │       │               │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think cookies are stored on the server or the client? Commit to your answer.
Common Belief:Cookies are stored on the server to keep track of users.
Tap to reveal reality
Reality:Cookies are stored on the client (browser), not the server. The server only sends instructions to set or delete cookies.
Why it matters:Thinking cookies are server-side can lead to security mistakes and confusion about how to manage user data.
Quick: Do you think cookies can store large files like images? Commit to your answer.
Common Belief:Cookies can store any amount of data, including large files.
Tap to reveal reality
Reality:Cookies have strict size limits (around 4KB) and cannot store large files. Large data should use other storage methods.
Why it matters:Trying to store too much data in cookies causes errors and slows down your app.
Quick: Do you think setting a cookie in Flask automatically makes it available in the next request? Commit to your answer.
Common Belief:Once you set a cookie in Flask, it is immediately available in the same request cycle.
Tap to reveal reality
Reality:Cookies set in the response are only sent to the browser and become available in subsequent requests, not the current one.
Why it matters:Expecting immediate availability leads to bugs where your app can't read newly set cookies until the next visit.
Quick: Do you think HttpOnly cookies can be accessed by JavaScript? Commit to your answer.
Common Belief:HttpOnly cookies can be read by JavaScript on the page.
Tap to reveal reality
Reality:HttpOnly cookies are inaccessible to JavaScript, protecting them from cross-site scripting attacks.
Why it matters:Misunderstanding this can cause security vulnerabilities by exposing sensitive cookies to scripts.
Expert Zone
1
Cookies set with the 'Secure' flag are only sent over HTTPS, preventing exposure on insecure connections.
2
The 'SameSite' attribute controls cross-site cookie sending, helping prevent CSRF attacks but can cause issues with third-party integrations.
3
Browsers limit the total number of cookies per domain, so managing cookie count is as important as size.
When NOT to use
Cookies are not suitable for storing large or sensitive data. For sensitive data, use server-side sessions with secure tokens. For large data, use browser storage like localStorage or IndexedDB. Also, avoid cookies for data that doesn't need to be sent with every request to reduce network overhead.
Production Patterns
In production, cookies are often used to store session IDs that link to server-side session data. Secure and HttpOnly flags are set to protect cookies. Developers use SameSite attributes to prevent CSRF. Cookies are kept minimal to optimize performance, and frameworks like Flask-Login handle cookie-based authentication securely.
Connections
HTTP Protocol
Cookies are part of HTTP headers used in requests and responses.
Understanding HTTP headers helps grasp how cookies travel between browser and server.
Web Security
Cookie attributes like HttpOnly and Secure relate directly to web security practices.
Knowing cookie security flags is essential to protect users from attacks like XSS and CSRF.
Human Memory
Cookies function like short-term memory notes that help websites remember users.
Seeing cookies as memory aids clarifies why they are limited in size and lifespan.
Common Pitfalls
#1Trying to read a cookie immediately after setting it in the same request.
Wrong approach:response = make_response('Set cookie') response.set_cookie('user', 'Alice') user = request.cookies.get('user') # This will be None return response
Correct approach:response = make_response('Set cookie') response.set_cookie('user', 'Alice') # Read cookie in a future request, not now return response
Root cause:Cookies set in the response are not available in the current request's cookie data.
#2Storing sensitive information like passwords directly in cookies.
Wrong approach:response.set_cookie('password', 'mypassword123')
Correct approach:Store only a session ID in the cookie and keep sensitive data securely on the server.
Root cause:Cookies can be read or intercepted if not properly secured, so sensitive data should never be stored directly.
#3Setting cookies without expiration, causing them to be session cookies unintentionally.
Wrong approach:response.set_cookie('theme', 'dark') # No expiration set
Correct approach:response.set_cookie('theme', 'dark', max_age=60*60*24*30) # Expires in 30 days
Root cause:Without expiration, cookies last only until the browser closes, which may not be the intended behavior.
Key Takeaways
Cookies are small pieces of data stored on the user's browser to help websites remember information between visits.
In Flask, you set cookies by adding them to the response object and read them from the request object.
Cookies have important attributes like expiration, HttpOnly, and Secure that control their behavior and security.
Cookies are limited in size and sent with every request, so keep them small to avoid performance issues.
Understanding how cookies work under the hood helps you avoid common mistakes and build secure, efficient web apps.