Skip to main content

Cookie Storage

What It Is

A cookie is a small piece of data stored by the browser and sent back to the server with later HTTP requests.

Cookies help web applications remember state because HTTP is stateless by default.

Cookie = Small key-value data stored in browser and sent with HTTP requests

Why It Matters

Cookies are useful when the server needs to remember something about the user or session across requests.

Unlike sessionStorage, cookies can persist across browser sessions.

Unlike localStorage, cookies can be automatically sent with HTTP requests.

Common uses:

  • session management
  • authentication session identifiers
  • user preferences
  • language settings
  • theme settings
Browser stores cookie -> Browser sends cookie with later requests -> Server remembers state

How Cookies Work

Cookies can be created by the server or by JavaScript.

The server usually sends cookies using the Set-Cookie HTTP header.

Set-Cookie: sessionId=abc123

After storing the cookie, the browser may send it back to the same server on future requests.

Cookie: sessionId=abc123

Cookies can also be created, updated, and read using JavaScript with document.cookie.


Basic JavaScript Usage

Cookies are stored as key-value pairs.

document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";

Read Cookies

console.log(document.cookie);

Output:

yummy_cookie=choco; tasty_cookie=strawberry

Setting a cookie with the same name updates its value.

document.cookie = "yummy_cookie=blueberry";

console.log(document.cookie);

Output:

tasty_cookie=strawberry; yummy_cookie=blueberry

Cookie attributes control where, when, and how cookies are used.

AttributePurpose
domainDefines which domain can receive the cookie
expiresSets cookie expiry using a date
max-ageSets cookie lifetime in seconds
SameSiteControls when cookie is sent in cross-site requests
SecureSends cookie only over HTTPS
HttpOnlyPrevents JavaScript access to the cookie
PathRestricts cookie to a specific path

Attributes are added after the key-value pair using semicolons.

document.cookie = "theme=dark; max-age=31536000; path=/";

Expiry and Max-Age

Cookies can be temporary or persistent.

If no expires or max-age is set, the cookie usually expires when the session ends.

Expires

document.cookie = "language=en; expires=Fri, 31 Dec 2027 23:59:59 GMT; path=/";

Max-Age

document.cookie = "language=en; max-age=31536000; path=/";

max-age defines how long the cookie should live in seconds.


SameSite

The SameSite attribute controls when cookies are sent with cross-site requests.

ValueMeaning
LaxSent for same-site requests and top-level navigation GET requests
StrictNot sent in cross-site browsing contexts
NoneSent in both same-site and cross-site requests

Modern browsers commonly use Lax as the default.

SameSite helps reduce Cross-Site Request Forgery risk.

Set-Cookie: sessionId=abc123; SameSite=Lax

Secure

The Secure attribute ensures cookies are sent only over secure protocols like HTTPS.

Set-Cookie: sessionId=abc123; Secure

Use Secure for cookies that should not travel over unencrypted HTTP connections.


HttpOnly

The HttpOnly attribute prevents JavaScript from accessing the cookie using document.cookie.

Set-Cookie: sessionId=abc123; HttpOnly

This improves security because client-side scripts cannot read the cookie.

It helps reduce risk if an XSS issue exists.

HttpOnly cookie -> browser sends it to server -> JavaScript cannot read it

Domain and Path

Domain controls which host can receive the cookie.

Path controls which URL path can receive the cookie.

Set-Cookie: userPref=dark; Domain=example.com; Path=/dashboard

These attributes help restrict where the cookie is available.

Use them carefully to avoid exposing cookies to unnecessary parts of the application.


Cookies can be session-based or persistent.

TypeBehavior
Session CookieExpires when the session ends
Persistent CookieExpires based on expires or max-age
No expiry set -> session cookie
Expiry set -> persistent cookie

Cookie persistence should match the purpose of the data.

Do not keep cookies longer than necessary.


Data Structure

Cookies store simple key-value data.

They can also include attributes such as:

  • expiry
  • max age
  • path
  • domain
  • secure flag
  • HttpOnly flag
  • SameSite value

Example:

Set-Cookie: theme=dark; Max-Age=31536000; Path=/; SameSite=Lax; Secure

Cookies are not suitable for complex or large data structures.


Size and Performance

Cookies have a small storage limit.

Each cookie can store around 4KB of data.

Performance matters because cookies are sent with HTTP requests.

Large or too many cookies can cause:

  • increased request size
  • extra bandwidth usage
  • higher latency
  • slower network communication
More cookie data -> larger HTTP requests

Keep cookies small and purposeful.


Security

Cookies can be more secure than JavaScript storage when configured correctly, but they must be handled carefully.

Important security practices:

  • use HttpOnly to block JavaScript access
  • use Secure to send cookies only over HTTPS
  • use SameSite to reduce CSRF risk
  • set proper Expires or Max-Age
  • restrict cookie scope using Domain and Path
  • avoid storing passwords, payment details, or personal data
  • do not keep cookies longer than needed
Secure cookie setup = HttpOnly + Secure + SameSite + proper expiry

When to Use

Use cookies when data needs to be sent with HTTP requests or used for session-related behavior.

Good use cases:

  • session management
  • authenticated session identifiers
  • server-readable preferences
  • language preference
  • theme preference

Example:

Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Lax

Cookies are useful when the server needs the value on future requests.


When Not to Use

Avoid cookies when the data is sensitive, large, or does not need to be sent with every HTTP request.

Do not use cookies for:

  • passwords
  • payment information
  • large data storage
  • unnecessary client-only state
  • data that should not be sent to the server
  • personal data without proper protection
If the server does not need it, avoid sending it in cookies.

Cookies vs localStorage vs sessionStorage

FeatureCookieslocalStoragesessionStorage
Sent with requestsYesNoNo
PersistenceSession or persistentPersistentTab session
SizeAround 4KB per cookieAround 5MB per domainAround 5MB per origin
Access from JSYes, unless HttpOnlyYesYes
Best forSession and server-readable dataSmall persistent client dataTemporary tab data
Security controlHttpOnly, Secure, SameSiteJavaScript accessibleJavaScript accessible

FeatureCookie Storage
PurposeStore small state data for browser and server
FormatKey-value pairs with optional attributes
PersistenceSession-based or persistent
Size limitAround 4KB per cookie
Request behaviorSent with HTTP requests
JavaScript accessAvailable unless HttpOnly is set
Security attributesHttpOnly, Secure, SameSite, Domain, Path
Best forSession management and server-readable preferences
Avoid forLarge data, passwords, personal data, payment data

Basic Checklist

Use cookies only for small data
Use cookies when server needs the value
Set proper expiry or max-age
Use HttpOnly for session cookies
Use Secure for HTTPS-only transmission
Use SameSite to reduce CSRF risk
Use Domain and Path to limit scope
Avoid storing sensitive raw data
Avoid storing large data
Do not overuse cookies because they are sent with requests

Interview Style Answer

Cookies are small key-value data stored by the browser and sent back to the server with later HTTP requests. They are useful because HTTP is stateless, so cookies help applications remember session or preference information. Cookies can be set by the server using the Set-Cookie header or manipulated using JavaScript through document.cookie. They can be session cookies or persistent cookies depending on expires or max-age. Cookies are limited to around 4KB each and are sent with HTTP requests, so large or excessive cookies can hurt performance. For security, cookies should use attributes like HttpOnly, Secure, SameSite, Domain, and Path, and should not store passwords, payment information, or sensitive personal data.


One-Line Summary

Cookie Storage = Small browser key-value storage that can persist and automatically travel with HTTP requests.

Final Mental Model

Need server to receive data automatically? -> Cookie
Need JavaScript-only persistent data? -> localStorage
Need tab-only temporary data? -> sessionStorage
Need secure session cookie? -> HttpOnly + Secure + SameSite
Need large data? -> Do not use cookies