logo
Published on

Cookie

Authors
  • avatar
    Name
    Bowen Y
    Twitter

A cookie is a small piece of data sent from a website and stored on the user's computer by the user's web browser while the user is browsing.

Cookies are used to remember information about the user for the duration of the visit (session cookies) or for repeat visits (persistent cookies). They can store preferences, session information, and other data to improve the user experience or track user behavior.

Cookies can be vulnerable to theft (via XSS attacks) or interception (if not secured with attributes like HttpOnly and Secure).

Name: sessionToken
Value: abc123
Domain: example.com
Path: /
Expires: Wed, 09 Jun 2024 10:18:14 GMT
Secure: true
HttpOnly: true
SameSite: Strict

A web cookie is essentially a small piece of plain text, not a JSON object or any other complex data structure.

Usage Example

Imagine a user visiting an e-commerce website for the first time. The website wants to track the user's session to keep items in the shopping cart as the user browses.

  • Action: The user adds an item to their shopping cart.
  • Behind the Scenes: The server sends a response to the user's browser with a Set-Cookie header. This header might include a cookie like session_id=12345.
  • Browser's Role: The user's browser stores this cookie and sends it back to the server with every subsequent request.
  • Result: The server identifies the session_id cookie in each request, allowing it to retrieve and maintain the state of that user's shopping cart.

how-cookie-works

Difference under the hood

The key differences among these methods(Cookie, Session, JWT) lie in how and where user data is stored and managed, as well as the specific use cases they are best suited for.

  • Storage Location: Directly on the user's browser.
  • Data Storage: Can store data directly (like preferences, session IDs, etc.).
  • Management: Managed by the browser. The server can set, read, and delete cookies via HTTP headers.
  • Use Case: Ideal for simple, small pieces of data that need to persist across sessions, like user preferences or session identifiers.
  • Security: Since they are stored client-side, they are more vulnerable to attacks like cross-site scripting (XSS). Secure attributes like HttpOnly and Secure can mitigate some risks.

Example Code

Python

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/set_theme/<theme>')
def set_theme(theme):
    resp = make_response(f"Theme set to {theme}")
    resp.set_cookie('theme', theme)
    return resp

@app.route('/')
def index():
    theme = request.cookies.get('theme', 'default')
    return f"The current theme is {theme}"

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

Golang

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func setCookieHandler(c *gin.Context) {
	c.SetCookie("user", "John Doe", 3600, "/", "localhost", false, false)
	c.String(http.StatusOK, "Cookie has been set")
}

func deleteCookieHandler(c *gin.Context) {
	c.SetCookie("user", "", -1, "/", "localhost", false, true)
	c.String(http.StatusOK, "Cookie has been deleted")
}

func getCookieHandler(c *gin.Context) {
	cookie, err := c.Cookie("user")
	if err != nil {
		c.String(http.StatusNotFound, "Cookie not found")
		return
	}
	c.String(http.StatusOK, "Cookie value: %s", cookie)
}

func helloWorld(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "Hello, world!",
	})
	getCookieHandler(c)
}

func main() {
	r := gin.Default()

	r.GET("/", helloWorld)

	r.GET("/login", setCookieHandler)

	r.GET("/logout", deleteCookieHandler)

	r.Run() // Listen and serve on 0.0.0.0:8080
}

document.cookie returns an empty string

If document.cookie in the browser console is returning an empty string despite setting a cookie using Gin (or any server-side framework), there are several potential reasons for this behavior:

HttpOnly Flag:

If the cookie is set with the HttpOnly flag, it cannot be accessed via JavaScript for security reasons. This flag is often used to prevent access to cookies that are meant for server-side use only, especially to mitigate the risk of Cross-Site Scripting (XSS) attacks.