Loading...

JavaScript Cookies

A cookie is a small text value the browser can send with requests to the same site. This page writes the preference theme=dark, reads it back, and shows theme / dark. A cookie is not a place for a password or an access token.

Not web storage

The storage page kept saved / lida / tea in localStorage. A cookie is different: the browser may attach it to later requests for its matching site and path. document.cookie is one semicolon-separated string, not an object. A missing name gives no value; it does not throw.

Write a small preference

The first theme=dark is the name and value. Path=/ makes it available across this site's paths. SameSite=Lax limits cross-site sending in common navigation cases. Secure means the browser sends it only over HTTPS. Writing document.cookie = "theme=dark; Path=/; SameSite=Lax; Secure" adds that pair among any other cookies that this page can read, so do not compare the entire string to one value.

Read one name from the string

Split on ;, then look for the name followed by =. The browser does not turn the string into an object for you. Decode the part after the equals sign.

Read the theme

javascript
function readCookie(name) {
const start = name + "=";
const pair = document.cookie
.split("; ")
.find((part) => part.startsWith(start));
return pair ? decodeURIComponent(pair.slice(start.length)) : null;
}
console.log(readCookie("theme"));
console.log(readCookie("drink"));

The logs are dark, then null. drink was never written. readCookie returns null for a missing name, just as getItem did for a missing storage key.

Encode a value that contains spaces

Cookie separators such as ; and = belong to cookie syntax. encodeURIComponent turns a value into safe text before it goes into the pair. decodeURIComponent restores it on the way out.

Save an encoded label

javascript
const label = "tea / regular";
document.cookie =
"last-order=" + encodeURIComponent(label) + "; Path=/; SameSite=Lax; Secure";
console.log(readCookie("last-order"));

The log is tea / regular. Do not put raw ; into a cookie value: it starts another cookie attribute. Encoding makes the boundary clear.

Cookie or localStorage?

Choose the box by who needs the value. Neither makes a secret safe from JavaScript that already runs on your page.

📊 Cookie and storage

Need Cookie localStorage
Sent with matching requests often yes no
Read from page JavaScript unless HttpOnly yes
Small visual preference possible usually simpler
Sensitive session identifier server sets HttpOnly + Secure do not store it here

HttpOnly is important for a session cookie, but JavaScript cannot set it and cannot read such a cookie. A server sends it in a Set-Cookie response header. This lesson uses a harmless theme preference, not authentication.

The line

The page saves dark, reads just the theme cookie, and writes the name with the value.

Page demo — theme cookie

html
<!DOCTYPE html>
<html>
<body>
<p id="line">…</p>
<script>
document.cookie = "theme=dark; Path=/; SameSite=Lax; Secure";
function readCookie(name) {
const start = name + "=";
const pair = document.cookie.split("; ")
.find((part) => part.startsWith(start));
return pair ? decodeURIComponent(pair.slice(start.length)) : null;
}
document.querySelector("#line").textContent =
"theme / " + readCookie("theme");
</script>
</body>
</html>

The line reads theme / dark. On plain HTTP, a browser can refuse the Secure cookie; the live site uses HTTPS. saved / lida / tea was the storage-page line.

At the counter

  1. Write theme=dark with Path=/ and read theme. The value is dark.
  2. Read drink before writing it. The value is null.
  3. Save tea / regular with encodeURIComponent. Read it back unchanged.
  4. Name the safe server-side flags for a session cookie: HttpOnly, Secure, and an appropriate SameSite value.
  5. Read the page. The line is theme / dark.

Misses

document.cookie is not a secret store and it is not a JavaScript object.

  • Putting a password or token in a JavaScript-readable cookie
  • Comparing the full cookie string to theme=dark
  • Forgetting Path=/ and wondering why another path cannot see the preference
  • Writing raw separators into a value instead of encoding it
  • Assuming JavaScript can create HttpOnly
  • Reading the line as saved / lida / tea

Keep this

  • A cookie is name=value text; document.cookie can contain several pairs
  • readCookie returns dark for theme and null for a missing name
  • Encode a value before writing it and decode it after reading
  • Use server-set HttpOnly, Secure, and SameSite for a session identifier
  • The page line is theme / dark

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top