iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Cookies

A cookie is a small named value the browser sends back to the server with every request to the same origin. Used for sessions, preferences, and analytics.

Reading and writing in JS

JS
// Read — semicolon-separated "name=value; name=value"
document.cookie;
// "session=abc; theme=dark"

// Write — one cookie per assignment
document.cookie = "theme=dark; path=/; max-age=31536000";

// Delete by setting an expired date
document.cookie = "theme=; path=/; max-age=0";

Important attributes

AttributeWhat it does
pathURL path this cookie is sent for. / = whole site.
domainHost scope. Leave unset for same host.
max-age / expiresHow long it lives. Without one, it dies on tab close.
secureOnly sent over HTTPS.
httponlyHidden from JS — only readable by the server. Cannot be set from JS.
samesitestrict, lax (default modern), or none.

Tiny helper functions

JS
const getCookie = (name) =>
  Object.fromEntries(
    document.cookie.split("; ").map(s => s.split("="))
  )[name];

const setCookie = (name, value, days = 365) => {
  document.cookie =
    `${name}=${encodeURIComponent(value)}; path=/; max-age=${days * 86400}; SameSite=Lax`;
};

When NOT to use cookies

NeedUse
Client-only preferenceslocalStorage — bigger, faster, not sent to server.
Auth tokens visible to JSHttpOnly cookies set by the server (safer against XSS).
Large blobsIndexedDB (cookies cap at ~4KB).
Tip: For tokens, always set Secure; HttpOnly; SameSite=Lax on the server. Reading auth tokens from document.cookie defeats the purpose.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Cookies!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Set a cookie that lasts a year on the whole site.

document.cookie = 'theme=dark; path=/; =31536000';

Test yourself

Q1. HttpOnly cookies are…
Q2. Delete a cookie by setting…
Q3. For client-only preferences, prefer…

Discussion

Loading…