← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 5 of 26

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?

javascript
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

javascript
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

javascript
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

javascript
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

javascript
// 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);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.