JS Cookies
What Is a Cookie?
A cookie is a small piece of data stored by a website in the browser. Unlike localStorage, cookies are automatically included in every HTTP request to their domain, which is what makes them useful for session identification.
Example: What Is a Cookie?
document.cookie = "username=Sam"; // automatically sent with future requests to this domain
console.log(document.cookie);
Read Cookies
document.cookie returns cookies available to the current document. The returned string contains all cookies as one semicolon-separated list, so reading a specific cookie's value requires parsing that string yourself.
Example: Read Cookies
document.cookie = "a=1";
document.cookie = "b=2";
console.log(document.cookie); // "a=1; b=2" - one semicolon-separated string
Cookie Expiration
You can set an expiration date or max-age for a cookie. Without an explicit expiration, a cookie is a 'session cookie' that disappears when the browser closes; setting one makes it persist until that date.
Example: Cookie Expiration
const expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
document.cookie = `username=Sam; expires=${expiry.toUTCString()}`;
console.log(document.cookie);
Delete a Cookie
To delete a cookie, set its expiration time to the past or max-age to zero. Browsers don't provide a dedicated delete method — overwriting the cookie with an already-past expiration date is the standard way to remove it.
Example: Delete a Cookie
document.cookie = "username=Sam; expires=Thu, 01 Jan 1970 00:00:00 UTC"; // deletes it
console.log(document.cookie);
Cookie Safety
Do not store sensitive data in ordinary JavaScript-readable cookies. Secure authentication cookies should normally use server-side security flags. Sensitive cookies like session tokens should be marked HttpOnly and Secure server-side so client-side JavaScript can't read or leak them, unlike the document.cookie access shown here.
Example: Cookie Safety
// Do NOT rely on document.cookie for sensitive data:
document.cookie = "theme=dark"; // fine, non-sensitive
// Session tokens should be set server-side with HttpOnly + Secure flags instead
console.log(document.cookie);
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML