← Back to Chapters

JavaScript Cookies

? JavaScript Cookies

⚡ Quick Overview

Cookies are small data strings stored in the user's browser. They are often used to remember information across pages or between visits, such as login sessions, theme preferences, or shopping cart contents.

In JavaScript, cookies are managed using the document.cookie property, which lets you create, read, update, and delete cookies for the current site.

? Key Concepts

  • Cookie: A small piece of text data stored by the browser for a specific website.
  • Session cookie: A cookie without an expiry date; it is deleted when the browser is closed.
  • Persistent cookie: A cookie with an expires or max-age attribute; it survives across browser sessions.
  • Attributes: Extra settings like expires, path, Secure, and SameSite that control cookie lifetime and scope.
  • Limitations: Typical size is about 4KB per cookie and a limited number of cookies per domain (around 20+).

? Syntax and Theory

The basic syntax for setting a cookie in JavaScript is:

document.cookie = "name=value";

You can add attributes to control the cookie's behavior:

  • expires=<date-string> – date and time after which the cookie will be deleted.
  • max-age=<seconds> – lifetime of the cookie in seconds.
  • path=/ – makes the cookie available across the entire site.

? Cookie Summary

Action Syntax
Create document.cookie = "key=value"
Read document.cookie
Update Set again using the same key
Delete Set expires to a past date

? Code Examples

? Create a simple session cookie
document.cookie = "username=JohnDoe";
⏰ Create a persistent cookie with expires
document.cookie = "username=JohnDoe;expires=Fri, 31 Dec 2025 23:59:59 UTC;path=/";
? Read all cookies for the current page
console.log(document.cookie);
// Example output:
// "username=JohnDoe; theme=dark"
✏️ Update an existing cookie
document.cookie = "username=JaneDoe";
?️ Delete a cookie by setting a past expiry date
document.cookie = "username=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;";
?️ Helper functions for set, get, and delete
function setCookie(name, value, days) {
  const d = new Date();
  d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
  const expires = "expires=" + d.toUTCString();
  document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + ";path=/";
}

function getCookie(name) {
  const cname = name + "=";
  const decoded = decodeURIComponent(document.cookie);
  const parts = decoded.split(";");
  for (let c of parts) {
    c = c.trim();
    if (c.indexOf(cname) === 0) {
      return c.substring(cname.length);
    }
  }
  return "";
}

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

? Live Output and Explanation

Below is a simple interactive example that stores your name in a cookie and shows a personalized greeting whenever you visit or reload the page.

? Greeting Demo Using Cookies



 

This example uses setCookie() and getCookie() to remember your name for a few days.

How it works:

  • When you click Save Name in Cookie, JavaScript writes a cookie like username=YourName with an expiry date.
  • On page load, JavaScript reads document.cookie, finds the username cookie, and shows a custom greeting if it exists.

? Common Use Cases

  • Remembering user login sessions (with secure, server-side cookies).
  • Storing UI preferences like language or theme selection.
  • Tracking visit counts or basic analytics (with user consent).
  • Maintaining shopping cart information between page loads.

? Tips and Best Practices

  • Use path=/ to make cookies accessible across your entire site.
  • Use encodeURIComponent() when storing values that may contain spaces or special characters.
  • Remember that cookies are small (~4KB), so avoid storing large or complex data.
  • For larger or structured data, consider using localStorage or sessionStorage instead of cookies.
  • If you need to store objects, convert them to strings using JSON.stringify() and parse with JSON.parse() when reading.
  • Do not store sensitive data in client-side cookies; rely on secure, server-side mechanisms and flags like Secure and HttpOnly (set from the server).
  • Always be aware of privacy and legal requirements (e.g., cookie consent banners) when tracking users.

? Try It Yourself

  • Create a cookie named theme and toggle between dark/light mode based on its value when the page loads.
  • Prompt the user for their name, store it in a cookie, and show a personalized greeting on the next visit.
  • Write a function that deletes all cookies when the user logs out of your site.
  • Detect first-time visitors using a visited=true cookie and show a welcome popup only for new visitors.