KAHIBARO
Discord Login Register

2.13. Cookies

Why Cookies Exist

Web servers do not remember you between requests. Every HTTP request is independent. If you refresh a page, the server sees it as a completely new request.

This makes it hard to:

Cookies solve this problem by letting the server store small pieces of data in the browser and get them back with future requests.

A cookie is simply:

A small name/value pair that the browser stores and automatically sends with matching requests.

Example idea:

How Cookies Work

Setting Cookies from the Server

Servers set cookies using the Set-Cookie HTTP response header.

Example HTTP response:

http
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: theme=dark
Set-Cookie: session_id=abc123

The browser reads these headers and stores two cookies:

NameValue
themedark
session_idabc123

On the next request to the same site, the browser will send them in the Cookie request header.

Example HTTP request:

http
GET /dashboard HTTP/1.1
Host: example.com
Cookie: theme=dark; session_id=abc123

The server can then read theme and session_id and customize the response.

Cookie Format

A single cookie is usually represented as:

text
name=value

Multiple cookies are separated by ; in the Cookie header:

http
Cookie: name1=value1; name2=value2; name3=value3

Cookie names and values are simple strings. Values can be URL encoded to store spaces or special characters, for example user=John%20Doe.

Cookie Attributes

Cookies are not only name=value. They include attributes that control how and when the browser sends them.

They are set in Set-Cookie responses like this:

http
Set-Cookie: session_id=abc123; Path=/; Domain=example.com; HttpOnly; Secure; SameSite=Lax; Expires=Wed, 01 Jan 2025 00:00:00 GMT

Important attributes:

AttributePurpose
ExpiresWhen the cookie should expire (absolute time)
Max-AgeHow long the cookie lives in seconds
DomainWhich domain(s) will receive this cookie
PathWhich path prefix must match for cookie to be sent
SecureOnly send over HTTPS
HttpOnlyNot accessible to JavaScript
SameSiteRestrict cross-site sending of cookies

Important rule: Cookies are controlled only by the server via Set-Cookie. Browsers automatically store and send them according to their attributes. As a backend developer you define exactly how long cookies live and where they can be used.

We will now look at each attribute in more detail.

Session vs Persistent Cookies

Session Cookies

A session cookie exists only while the browser is open. Once the user closes all browser windows for that site, the cookie disappears.

A cookie becomes a session cookie when you do not specify Expires or Max-Age.

Example:

http
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax

Characteristics:

Persistent Cookies

A persistent cookie survives browser restarts and is stored on disk. It is created by specifying either:

Example with Expires:

http
Set-Cookie: theme=dark; Expires=Wed, 01 Jan 2025 00:00:00 GMT; Path=/

Example with Max-Age:

http
Set-Cookie: remember_me=true; Max-Age=2592000; Path=/  ; 30 days

Approximate conversions:

DaysSeconds
186400
7604800
302592000
36531536000

Rule: Any cookie with Expires or Max-Age is persistent. Any cookie without them is a session cookie.

Use persistent cookies to remember preferences such as theme or language. Use session cookies for temporary state such as login sessions, unless you have a specific reason to persist longer.

Domain and Path Scoping

Cookies are not sent to every website. They are limited by Domain and Path.

Domain Attribute

Domain controls which hostnames receive the cookie.

Examples:

http
Set-Cookie: lang=en; Path=/; Domain=example.com

Sent to:

Not sent to:

Without Domain:

http
Set-Cookie: token=abc; Path=/account

Set from api.example.com. It will not be sent to example.com or shop.example.com, only to api.example.com.

Path Attribute

Path is a URL path prefix. The browser sends the cookie only for URLs that start with that path.

Examples:

http
Set-Cookie: cart_id=123; Path=/shop

Sent for:

Not sent for:

Another example:

http
Set-Cookie: admin_token=xyz; Path=/admin

This helps separate cookies used for admin areas from others.

Rule: The browser sends a cookie only if:

  1. The request domain matches the cookie Domain
  2. The request path starts with the cookie Path
  3. Other security rules such as Secure and SameSite also allow it

Secure and HttpOnly Cookies

These two attributes improve security without changing the cookie value itself. They only affect how the browser behaves.

Secure

Secure means the browser will send the cookie only over HTTPS.

Example:

http
Set-Cookie: session_id=abc123; Path=/; Secure

This cookie will be sent with:

You should always use Secure for any cookie that has sensitive information such as session IDs, tokens, or user identifiers.

HttpOnly

HttpOnly means JavaScript in the browser cannot read or write this cookie via document.cookie.

Example:

http
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure

Effects:

Cookie accessibility table:

Cookie attributeHTTP requestsJavaScript access
No HttpOnlyYesYes
With HttpOnlyYesNo

Use HttpOnly for session cookies and authentication tokens.

Rule: Authentication cookies should be both Secure and HttpOnly in production. This protects them from network sniffing and JavaScript access.

SameSite and Cross-Site Cookies

SameSite controls when cookies are sent in cross-site requests. This is important for preventing CSRF attacks and for understanding login behavior across different domains.

Common values:

SameSite=Strict

The browser sends the cookie only for requests that originate from the same site.

Strict is the safest, but sometimes too strict for normal flows.

SameSite=Lax

This is more relaxed and often the default.

Example:

http
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax

Good default for normal login sessions that do not need complex cross-site behavior.

SameSite=None; Secure

This allows the cookie to be sent in cross-site requests such as:

But, to use SameSite=None, browsers require Secure.

http
Set-Cookie: sso_token=xyz; Path=/; SameSite=None; Secure

Use this when you intentionally need cross-site cookies, for example single sign-on systems.

Rule: If you set SameSite=None, you must also set Secure. Otherwise, many browsers will ignore the cookie.

Reading and Using Cookies in Backend Code

As a backend developer, you usually:

  1. Read cookies from the incoming request
  2. Use them to identify or customize the user
  3. Set or update cookies in the response

The exact code depends on your framework, but the ideas are the same.

Example in Python with a Simple Framework (Conceptual)

Imagine a minimal Python backend:

python
def handle_request(request):
    # Reading cookies from the request
    cookies = request.cookies       # e.g. {"theme": "dark", "session_id": "abc123"}
    theme = cookies.get("theme", "light")
    # Use cookie value in logic
    if theme == "dark":
        body = "<body class='dark'>Welcome</body>"
    else:
        body = "<body>Welcome</body>"
    # Creating a response and setting a cookie
    response = Response(body=body, status=200)
    response.set_cookie(
        key="last_visit",
        value="2026-08-27",
        max_age=86400,
        path="/",
        httponly=False,
        secure=True,
        samesite="Lax",
    )
    return response

Breakdown:

Resulting response header might be:

http
Set-Cookie: last_visit=2026-08-27; Max-Age=86400; Path=/; Secure; SameSite=Lax

Raw HTTP Example

You can also think in plain HTTP:

  1. First request, no cookie yet:
http
GET / HTTP/1.1
Host: example.com

Server responds:

http
HTTP/1.1 200 OK
Set-Cookie: theme=dark; Path=/; Max-Age=31536000
Content-Type: text/html
<html>...</html>
  1. Second request, browser includes the cookie:
http
GET /profile HTTP/1.1
Host: example.com
Cookie: theme=dark

Server reads theme and sends a dark themed page.

Common Uses of Cookies

Cookies by themselves are just small key-value storage. How you use them defines their purpose.

Session Management

The most important use for backend developers.

Typical pattern:

  1. User logs in with username and password
  2. Server validates credentials
  3. Server creates a session record in the database

Example table:

| session_id | user_id | created_at | expires_at |
|-----------|---------|----------------------|----------------------|
| abc123 | 42 | 2026-08-27 10:00:00 | 2026-08-27 18:00:00 |

  1. Server sets cookie:
http
   Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
  1. On every next request:
    • Browser sends Cookie: session_id=abc123
    • Server looks up session_id in the session table
    • Finds user_id=42
    • Treats the request as authenticated as user 42

You never store the password or full user data in the cookie, only a random session ID.

Remembering Preferences

Examples:

Cookies for preferences:

Example:

http
Set-Cookie: lang=en; Max-Age=31536000; Path=/; SameSite=Strict

Tracking and Analytics

Analytics tools may use cookies to:

As a backend developer, you should be aware of privacy laws such as GDPR, which may require asking user consent before setting certain cookies.

Cookie Size and Limits

Cookies are not for storing large data. They have limits.

Typical restrictions in browsers:

If you try to store too much data:

Rule: Never store large or sensitive data such as passwords, full profiles, or big JSON blobs in cookies. Store only small identifiers, for example a session ID, and keep the real data on the server.

Performance Impact

Cookies are sent with every request to the matching domain and path. Large cookies mean:

Good practice: Keep cookies small and limited in number.

Security Considerations

Cookies are heavily related to security. You will learn attacks such as XSS and CSRF in the security section, but here is what relates directly to cookies.

Sensitive Data

Never store these in cookies:

Instead, store:

Use Secure and HttpOnly

For authentication cookies and any cookie that proves identity:

Example best practice:

http
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax

SameSite and CSRF

SameSite can help reduce Cross-Site Request Forgery attacks:

You will learn more when you study CSRF, but remember that cookies are a big part of that story.

Expiration and Logout

When a user logs out, you should:

  1. Delete or invalidate the server-side session
  2. Tell the browser to remove the cookie by setting an expired cookie

Example logout response:

http
Set-Cookie: session_id=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; Secure; SameSite=Lax

This tells the browser to remove session_id.

Summary

You now know the essentials of cookies from a backend perspective:

In later chapters about sessions and security, you will build on this knowledge and see exactly how cookies combine with server-side storage to implement robust authentication systems.

Views: 15

Comments

Please login to add a comment.

Don't have an account? Register now!