πŸͺ Cookies in JavaScript – Complete Tutorial

Cookies are small pieces of data stored in the user's browser. They are commonly used to remember user preferences, maintain login sessions, store authentication tokens (carefully), and track user activity.

πŸ“Œ What are Cookies?

A cookie is a small text value that a website stores in the browser. Every time the browser sends a request to the same website, the cookie is automatically included in the request (subject to its settings).

>>"Cookies help websites remember information about users between requests."

πŸ’‘ Why Use Cookies?

  • πŸ‘€ Remember logged-in users
  • 🌐 Save language preferences
  • πŸ›’ Store shopping cart information
  • 🎨 Save theme settings (Dark/Light mode)
  • πŸ“Š Analytics and tracking

πŸͺ Cookie Syntax

Cookies are managed using the document.cookie property.

Basic Cookie Syntax

document.cookie = "username=John";

The cookie is stored as a string in the browser.

πŸ“ Creating a Cookie

Create Cookie

document.cookie = "username=John";

This creates a session cookie, which is removed when the browser closes.

πŸ“– Reading Cookies

Read Cookies

console.log(document.cookie);

If multiple cookies exist, they are returned as a semicolon-separated string.

Example Output

username=John; theme=dark; language=en

✏️ Updating a Cookie

To update a cookie, assign a new value using the same cookie name.

Update Cookie

document.cookie = "username=Alice";

πŸ—‘οΈ Deleting a Cookie

Cookies are deleted by setting their expiration date to a time in the past.

Delete Cookie

document.cookie =
  "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

⏳ Cookie Expiration

You can specify how long a cookie should remain stored.

Cookie with Expiration

document.cookie =
  "username=John; expires=Fri, 31 Dec 2027 23:59:59 UTC; path=/";

Note

Without an expiration date, the cookie becomes a session cookie.

πŸ“‚ Cookie Path

The path attribute controls where the cookie is accessible.

Cookie Path

document.cookie =
  "theme=dark; path=/";

Setting path=/ makes the cookie available across the entire website.

πŸ”’ Secure Cookies

Security attributes help protect cookies from unauthorized access.

AttributeDescription
SecureSent only over HTTPS.
HttpOnlyCannot be accessed by JavaScript (server-set only).
SameSiteHelps protect against CSRF attacks.

Secure Cookie

document.cookie =
  "theme=dark; Secure; SameSite=Strict";

Note

HttpOnly cannot be added using JavaScript. It must be set by the server.

πŸ› οΈ Helper Functions

Set Cookie

setCookie()

function setCookie(name, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);

  document.cookie =
    name +
    "=" +
    encodeURIComponent(value) +
    "; expires=" +
    date.toUTCString() +
    "; path=/";
}

Get Cookie

getCookie()

function getCookie(name) {
  const cookies = document.cookie.split(";");

  for (let cookie of cookies) {
    const c = cookie.trim();

    if (c.startsWith(name + "=")) {
      return decodeURIComponent(c.substring(name.length + 1));
    }
  }

  return null;
}

Delete Cookie

deleteCookie()

function deleteCookie(name) {
  document.cookie =
    name +
    "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
}

πŸš€ Example

Complete Example

setCookie("username", "John", 7);

console.log(getCookie("username"));

deleteCookie("username");

πŸ“Š Cookie vs Local Storage vs Session Storage

FeatureCookiesLocal StorageSession Storage
Storage Limit~4 KB~5–10 MB~5 MB
ExpiresConfigurableNever (until cleared)Tab closes
Sent to Serverβœ… Yes❌ No❌ No
Accessible by JSUsually YesYesYes

⚠️ Best Practices

  • πŸ”’ Use HTTPS with the Secure attribute.
  • πŸ›‘οΈ Use SameSite=Lax or SameSite=Strict to reduce CSRF risk.
  • 🚫 Avoid storing sensitive data such as passwords in cookies.
  • πŸ“¦ Keep cookie values small (typically under 4 KB).
  • πŸ”‘ Use server-set HttpOnly cookies for authentication tokens when possible.
  • 🧹 Remove cookies that are no longer needed.

🎯 Summary

JavaScript cookies allow websites to store small amounts of information in the browser. You can create, read, update, and delete cookies usingdocument.cookie. While cookies are useful for sessions and user preferences, modern web applications often use localStorage orsessionStorage for client-side data that does not need to be sent with every HTTP request.