0
0
Flaskframework~15 mins

How cookies work in HTTP in Flask - Mechanics & Internals

Choose your learning style9 modes available
Overview - How cookies work in HTTP
What is it?
Cookies are small pieces of data that websites store on your browser to remember information about you. When you visit a website, the server can send a cookie to your browser, which saves it and sends it back with future requests. This helps websites recognize you, keep you logged in, or remember your preferences. Cookies work through HTTP headers that travel between your browser and the server.
Why it matters
Without cookies, websites would treat every visit as brand new, forgetting who you are each time. This would mean no saved logins, no shopping carts, and no personalized experiences. Cookies solve this by letting websites keep track of your session and preferences, making the web feel more like a continuous conversation rather than a series of strangers meeting every time.
Where it fits
Before learning about cookies, you should understand basic HTTP requests and responses. After cookies, you can explore sessions and authentication in web frameworks like Flask. Later, you might learn about security topics like HTTPS, SameSite cookies, and Cross-Site Request Forgery (CSRF) protection.
Mental Model
Core Idea
Cookies are like name tags your browser wears to every website visit, so the website remembers who you are and what you like.
Think of it like...
Imagine going to a coffee shop where the barista gives you a small card with your name and favorite drink. Every time you come back, you show the card, and they know exactly what you want without asking again.
┌───────────────┐       ┌───────────────┐
│   Browser     │       │    Server     │
│               │       │               │
│ 1. Sends HTTP ├──────▶│               │
│    request    │       │               │
│               │       │ 2. Responds   │
│               │◀──────┤ with Set-Cookie│
│ 3. Stores    │       │   header      │
│    cookie     │       │               │
│               │       │               │
│ 4. Sends HTTP ├──────▶│               │
│    request    │       │               │
│    with cookie│       │               │
└───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is an HTTP Cookie
🤔
Concept: Introduce the basic idea of cookies as small data pieces stored by browsers.
When you visit a website, the server can send a small piece of text called a cookie to your browser. Your browser saves this cookie and sends it back to the server with every new request to that website. This helps the server remember you between visits.
Result
The browser stores the cookie and includes it in future requests to the same website.
Understanding that cookies are simple text data sent and received via HTTP headers is the foundation for how websites remember users.
2
FoundationHow Cookies Travel in HTTP Headers
🤔
Concept: Explain the HTTP headers involved in sending and receiving cookies.
Servers send cookies using the 'Set-Cookie' header in HTTP responses. Browsers send cookies back using the 'Cookie' header in HTTP requests. For example, a server response might include: Set-Cookie: sessionId=abc123; Path=/; HttpOnly. Then, the browser sends: Cookie: sessionId=abc123 in future requests.
Result
Cookies are exchanged automatically between browser and server through HTTP headers.
Knowing the exact headers involved clarifies how cookies are part of the HTTP conversation, not separate data.
3
IntermediateCookie Attributes and Their Effects
🤔Before reading on: do you think cookies can control where and how they are sent? Commit to yes or no.
Concept: Introduce cookie attributes like Path, Domain, Secure, HttpOnly, and SameSite that control cookie behavior.
Cookies can have extra settings called attributes. For example, 'Path' limits which URLs send the cookie, 'Secure' means the cookie is only sent over HTTPS, 'HttpOnly' prevents JavaScript from reading the cookie, and 'SameSite' controls cross-site sending to improve security.
Result
Cookies behave differently based on their attributes, affecting security and scope.
Understanding cookie attributes is key to controlling security and privacy in web applications.
4
IntermediateUsing Cookies in Flask Applications
🤔Before reading on: do you think Flask sets cookies by modifying the response or the request? Commit to your answer.
Concept: Show how to set and read cookies in Flask using response and request objects.
In Flask, you set cookies by modifying the response object with response.set_cookie('key', 'value'). To read cookies, use request.cookies.get('key'). For example: from flask import Flask, request, make_response app = Flask(__name__) @app.route('/set') def set_cookie(): resp = make_response('Cookie set') resp.set_cookie('username', 'Alice') return resp @app.route('/get') def get_cookie(): user = request.cookies.get('username') return f'Hello {user}' if user else 'Hello guest'
Result
Flask apps can store and retrieve user data across requests using cookies.
Knowing how to handle cookies in Flask connects the HTTP concept to practical web development.
5
IntermediateSession Management Using Cookies
🤔
Concept: Explain how cookies help maintain user sessions by storing session IDs.
Websites often use cookies to store a session ID, a unique code that links the browser to server-side data. When the browser sends the session ID cookie, the server knows which user is making the request and can load their data, like login status or shopping cart contents.
Result
Users stay logged in and have personalized experiences across multiple page visits.
Understanding sessions as a combination of cookies and server data explains how websites keep track of users securely.
6
AdvancedSecurity Risks and Mitigations with Cookies
🤔Before reading on: do you think cookies can be stolen by other websites or scripts? Commit to yes or no.
Concept: Discuss common security risks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF), and how cookie attributes help prevent them.
Cookies can be stolen if a website allows malicious scripts (XSS) or tricked into sending unwanted requests (CSRF). Using 'HttpOnly' prevents JavaScript access to cookies, 'Secure' ensures cookies only travel over HTTPS, and 'SameSite' restricts cross-site cookie sending to reduce CSRF risks.
Result
Proper cookie settings reduce the chance of attacks stealing or misusing cookies.
Knowing cookie security features helps build safer web applications and protect user data.
7
ExpertBrowser Cookie Storage and Limits
🤔Before reading on: do you think browsers store unlimited cookies per site? Commit to yes or no.
Concept: Reveal how browsers store cookies, their size limits, and how they manage many cookies per domain.
Browsers limit cookie size to about 4KB per cookie and limit the number of cookies per domain (usually around 20-50). When limits are exceeded, older cookies get deleted. Cookies are stored as plain text files or databases inside the browser profile. This means developers must keep cookies small and manage them carefully.
Result
Understanding storage limits prevents bugs caused by lost or ignored cookies.
Knowing browser limits on cookies helps design efficient and reliable cookie usage in production.
Under the Hood
When a browser sends an HTTP request, it includes a 'Cookie' header with all relevant cookies for that domain and path. The server reads this header to identify the user or session. When responding, the server can send a 'Set-Cookie' header to create or update cookies. Browsers store cookies locally and automatically attach them to matching requests. Cookie attributes control when and how cookies are sent or accessible, enforced by the browser.
Why designed this way?
Cookies were designed to add state to the stateless HTTP protocol, enabling websites to remember users without changing the protocol itself. Using headers keeps cookies compatible with existing HTTP infrastructure. Attributes were added over time to improve security and privacy as web threats evolved.
┌───────────────┐          ┌───────────────┐
│   Browser     │          │    Server     │
│               │          │               │
│ Stores cookies│          │ Reads 'Cookie'│
│ in local file │          │ header on req │
│               │          │               │
│ Sends 'Cookie'│─────────▶│               │
│ header in req │          │               │
│               │          │ Sends 'Set-   │
│               │◀─────────│ Cookie' header│
│               │          │ in response   │
└───────────────┘          └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do cookies store your password directly? Commit to yes or no.
Common Belief:Cookies store sensitive data like passwords directly on your browser.
Tap to reveal reality
Reality:Cookies usually store session IDs or tokens, not passwords. Passwords are never stored in cookies for security reasons.
Why it matters:Storing passwords in cookies risks theft and account compromise if cookies are intercepted.
Quick: Do cookies work the same across all websites automatically? Commit to yes or no.
Common Belief:Cookies set by one website can be read by any other website you visit.
Tap to reveal reality
Reality:Cookies are restricted by domain and path. Only the website that set a cookie can read it, preventing other sites from accessing it.
Why it matters:Misunderstanding this can lead to privacy fears or incorrect assumptions about cross-site tracking.
Quick: Are cookies sent only once when first set? Commit to yes or no.
Common Belief:Cookies are sent only once when the server sets them and not on every request.
Tap to reveal reality
Reality:Cookies are sent with every HTTP request matching their domain and path until they expire or are deleted.
Why it matters:Not knowing this can cause unexpected data being sent repeatedly, affecting performance and privacy.
Quick: Can JavaScript always read all cookies? Commit to yes or no.
Common Belief:JavaScript can read all cookies stored by the browser for a website.
Tap to reveal reality
Reality:Cookies with the 'HttpOnly' attribute cannot be accessed by JavaScript, protecting them from certain attacks.
Why it matters:Assuming JavaScript can read all cookies leads to security risks and improper handling of sensitive data.
Expert Zone
1
Cookies with the 'SameSite=None' attribute must also have 'Secure' set, or browsers will reject them, a subtle but critical security rule.
2
Browsers may limit total cookie storage per domain differently, causing inconsistent behavior across users if not accounted for.
3
The order of cookies in the 'Cookie' header can affect server-side parsing in rare cases, so cookie naming and management matter.
When NOT to use
Cookies are not suitable for storing large amounts of data or highly sensitive information. Alternatives include localStorage for larger client-side data (though less secure) or server-side sessions with tokens. For stateless APIs, tokens like JWTs passed in headers are preferred over cookies.
Production Patterns
In production Flask apps, cookies often store session IDs linked to server-side session stores like Redis. Secure, HttpOnly, and SameSite attributes are set to protect user data. Cookies are combined with CSRF tokens in forms to prevent attacks. Developers also implement cookie expiration and renewal strategies to balance user experience and security.
Connections
HTTP Sessions
Cookies store session IDs that link to server-side session data.
Understanding cookies is essential to grasp how sessions maintain user state across stateless HTTP requests.
Web Security
Cookie attributes like HttpOnly and SameSite are key tools in web security defenses.
Knowing cookie mechanics helps understand and implement protections against common web attacks like XSS and CSRF.
Human Memory
Cookies function like short-term memory for websites, remembering recent interactions.
Seeing cookies as memory storage clarifies why they are limited in size and duration, similar to how humans remember recent events but forget details over time.
Common Pitfalls
#1Setting cookies without security attributes on sensitive data.
Wrong approach:resp.set_cookie('sessionId', 'abc123')
Correct approach:resp.set_cookie('sessionId', 'abc123', secure=True, httponly=True, samesite='Lax')
Root cause:Not understanding the importance of cookie attributes leads to insecure cookies vulnerable to theft.
#2Trying to read cookies from the request before they are set in the response.
Wrong approach:user = request.cookies.get('username') # immediately after setting cookie in same request
Correct approach:Set cookie in response, then read cookie in a subsequent request.
Root cause:Confusing the request-response cycle and when cookies become available in the browser.
#3Storing large data directly in cookies.
Wrong approach:resp.set_cookie('cart', large_json_string)
Correct approach:Store cart data server-side and save only a session ID in the cookie.
Root cause:Misunderstanding cookie size limits and performance implications.
Key Takeaways
Cookies are small pieces of data stored by browsers to help websites remember users and preferences.
They travel between browser and server using HTTP headers called 'Set-Cookie' and 'Cookie'.
Cookie attributes control their scope, security, and accessibility, which is vital for safe web applications.
In Flask, cookies are set on responses and read from requests, enabling session management and personalization.
Understanding cookie limits and security risks helps build reliable and secure web applications.