Back to JavaScript Notes
Topic #389

Cookies

By the end of this lesson, you will be able to store, read, and update small client-side values in JavaScript using cookies, and know when cookies are the right storage choice.

What it is

A cookie is a small name=value string that a browser stores for a website. Cookies are sent back to the server with HTTP requests, which makes them useful for state that the server needs to see. In JavaScript, you can create or update a cookie by assigning a string to document.cookie. Related terms include localStorage, sessionStorage, cookie attributes such as path, domain, expires, max-age, secure, and SameSite, and HttpOnly cookies that JavaScript cannot read.

Why it matters

  • Remember user preferences such as theme, language, or layout.
  • Carry session identifiers or security tokens to the server.
  • Store lightweight state that must survive page reloads and browser restarts.
  • Support analytics or marketing identifiers when privacy rules are followed.
  • Provide a simple fallback when server-side sessions are not available.

Syntax or steps

The smallest useful pattern is:

document.cookie = "theme=dark";

This creates or updates a cookie named theme with the value dark. It does not erase other cookies. For a persistent cookie, add attributes separated by semicolons:

document.cookie = "theme=dark; expires=Wed, 01 Jan 2031 00:00:00 UTC; path=/; SameSite=Lax";

Use encodeURIComponent() for names and values, and decodeURIComponent() when reading them. On HTTPS sites, add Secure.

Example

function setCookie(name, value, days) {
  const expires = new Date(Date.now() + days * 86400000).toUTCString();
  document.cookie =
    encodeURIComponent(name) + "=" +
    encodeURIComponent(value) + "; expires=" + expires +
    "; path=/; SameSite=Lax";
}

function getCookie(name) {
  const target = encodeURIComponent(name) + "=";
  const parts = document.cookie.split("; ");
  for (const part of parts) {
    if (part.startsWith(target)) {
      return decodeURIComponent(part.slice(target.length));
    }
  }
  return null;
}

setCookie("theme", "dark", 30);
console.log(getCookie("theme")); // "dark"

The setCookie() function builds a cookie string. The expires attribute makes the cookie last for the given number of days. The path=/ attribute makes it available to the whole site. The SameSite=Lax attribute reduces some cross-site request risks. The getCookie() function reads document.cookie, splits it into individual cookie pairs, finds the matching name, and decodes the value.

Common mistakes

  • Forgetting path=/. A cookie set from /app/page.html may not be visible on other pages.
  • Not encoding values. Spaces, semicolons, and equals signs can break the cookie string.
  • Trying to read an HttpOnly cookie with JavaScript. HttpOnly cookies are hidden from document.cookie for security.
  • Assuming assignment replaces all cookies. Each assignment adds or updates one cookie.

When to use it

StorageBest forLimitations
CookiesSmall data the server needs, such as session IDs or preferencesSent with requests, size-limited, and affected by security attributes
localStorageClient-only data that should persist across sessionsNot sent to the server automatically
sessionStorageTemporary data for one browser tabLost when the tab closes

Use cookies when the server must receive the value. Use localStorage or sessionStorage when the data is only needed in the browser.

Practice

Guided exercise: write a function called setTheme() that stores the current theme in a cookie named theme for 7 days, then read it back and log it.

Challenge: write a deleteCookie() function that removes a cookie by setting its expiration date in the past.

Expected output for the guided exercise: dark if you call setTheme("dark") and then read the cookie. Hint for the challenge: use the same name and path as the original cookie, and set max-age=0 or an expires date in the past.

Quick check

Question: Why might document.cookie return an empty string even after a cookie was set by the server?

Answer: The cookie may be marked HttpOnly, which prevents JavaScript from reading it.

Summary

Cookies are small client-side strings that can be created and read with document.cookie. They are most useful when the server needs to see the stored value, such as for sessions or preferences. Choose cookies deliberately, encode values, set appropriate attributes, and use browser storage APIs when server visibility is not required.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Cookies – FAQs

Quick answers about learning Cookies in JavaScript.

This free note from Coding Now Tech Institute explains Cookies in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Cookies, is 100% free with no signup required.
With focused practice, most students grasp Cookies in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now