Advance JavaScript (DOM, BOM, Web API) / Web API

Client Storages - Cookies

πŸͺ Cookie

  • A cookie is a small piece of data that a server sends to your browser.

  • The browser stores it on your computer and sends it back to the same server on future requests.

  • Also called web cookie or browser cookie.

Example

πŸ§‘β€πŸ’» 1. User logs into a website

You open amazon.com and log in.

The server checks your credentials and responds with:

HTTP/1.1 200 OK
Set-Cookie: sessionId=ABCD1234; HttpOnly; Secure
Content-Type: text/html

πŸ‘‰ What this means:

  • sessionId=ABCD1234 β†’ A unique ID created for your login session

  • Browser stores this cookie secretly

  • HttpOnly β†’ JavaScript cannot access it (security)

  • Secure β†’ Only sent over HTTPS


πŸ“€ 2. Browser automatically sends the cookie later

Now you click β€œMy Orders”, the browser sends:

GET /my-orders HTTP/1.1
Cookie: sessionId=ABCD1234

πŸ‘‰ What the server does:

  • Looks at the cookie

  • Recognizes: β€œOh, this is the same logged-in user”

  • Shows your orders without asking you to log in again


❓Why cookies

  • HTTP is stateless β†’ Every request is treated separately.

    The server cannot tell if two requests are from the same user.

  • Cookies solve this by letting the server identify the browser across multiple requests.

  • In practice, cookies serve the following purposes :

    • Session management β†’ Keep users logged in, store cart items, remember ongoing sessions.

    • Tracking β†’ Understand user activity (mostly used in ads/analytics).

    • Personalization β†’ Save user preferences like theme, language, layout, etc.


🚧 Cookie details

A cookie stored by the browser has the following parts:

  • Name β†’ Unique identifier (case-insensitive).

  • Value β†’ The data stored (must be URL-encoded).

  • Domain β†’ Which website the cookie belongs to.

  • Path β†’ Which pages of the website can access the cookie.

  • Expiration β†’ When the cookie should be deleted (stored even after the browser closes).

  • Secure flag β†’ Cookie is sent only over HTTPS.

Set-Cookie: user=john; 
expire=Tue, 12-December-2030 12:10:00 GMT; 
domain=javascripttutorial.net; 
path=/dom; 
secure

πŸ‘€ Cookies in JavaScript

You can get, set, and delete cookies in JavaScript using the document.cookie property.

1️⃣ Get Cookies

const str = document.cookie;

This returns a string like:

name1=value1; 
name2=value2; 
name3=value3

If values are encoded, use:

decodeURIComponent(value)

2️⃣ Set a Cookie

Format:

name=value; 
expires=date; 
path=/; 
domain=example.com; 
secure

Basic example:

document.cookie = "username=admin";
  • This creates a cookie named username with value admin.

  • No expiry β†’ cookie is deleted when the browser closes (session cookie).

Good practice (always encode):

document.cookie = `${encodeURIComponent("username")}=${encodeURIComponent("admin")}`;

3️⃣ Remove a Cookie

To delete a cookie β†’ set the same cookie again but with an expiration date in the past.

Example:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

🟫 View cookies with web browsers

  • To view the cookies on the web browser, you use the devtools.

    • First, inspect the browser

    • Second, click the application tab.

    • Third, select Cookies node under the Storage.

  • The following picture shows the cookies of Google.com :