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
| Attribute | What it does |
|---|---|
path | URL path this cookie is sent for. / = whole site. |
domain | Host scope. Leave unset for same host. |
max-age / expires | How long it lives. Without one, it dies on tab close. |
secure | Only sent over HTTPS. |
httponly | Hidden from JS — only readable by the server. Cannot be set from JS. |
samesite | strict, 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
| Need | Use |
|---|---|
| Client-only preferences | localStorage — bigger, faster, not sent to server. |
| Auth tokens visible to JS | HttpOnly cookies set by the server (safer against XSS). |
| Large blobs | IndexedDB (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';
Hyphenated attribute name.
Discussion
Loading…