🍪 Cookies
Last Updated: 26th October 2025
Cookies are small pieces of data stored by the browser on the client side.
They are mainly used to remember information about users between page reloads or visits.
Hinglish Tip 🗣: Cookies ko aise samjho — chhoti notes jo browser me store hoti hain, jaise username ya preferences ya shopping cart.
⚙️ Key Features
- Stored in key-value pairs.
- Sent automatically to server with every HTTP request (if domain matches).
- Can have expiration time.
- Max size ~4KB per cookie.
- Use for session tracking, preferences, login info.
Basic Cookie Syntax
1. Create / Set Cookie
document.cookie = "username=Sadhu";
document.cookie = "theme=dark; expires=Fri, 31 Oct 2025 23:59:59 GMT";
2. Read Cookie
const cookies = document.cookie;
console.log(cookies); // username=Sadhu; theme=dark
3. Delete Cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
⚡ Cookie Attributes
- name: The name of the cookie.
- value: The value of the cookie.
- expires: The expiration date of the cookie.
- max-age: The maximum age of the cookie in seconds.
- path: The path of the cookie.
- domain: The domain of the cookie.
- secure: Whether the cookie should only be sent over HTTPS.
- SameSite: The SameSite attribute of the cookie.
- Strict: The cookie is only sent if the request is made over HTTPS.
- Lax: The cookie is sent regardless of the request protocol.
- None: The cookie is sent regardless of the request origin.
Example:
document.cookie =
"username=Sadhu; expires=Fri, 31 Oct 2025 23:59:59 GMT; path=/; domain=.example.com; max-age=3600; secure; SameSite=Lax";
Hinglish Tip 🗣: Cookies ko handle karte waqt path, domain, secure, and SameSite samajhna bohot zaroori hai, nahi to unexpected behavior milega.
💡 Use Cases
- Remember user login / authentication
- Save theme preferences
- Track user session across pages
- Store temporary cart items on e-commerce websites
🧠 Quick Practice
- Set a cookie called language with value English for 1 day.
- Retrieve the language cookie and log it.
- Delete the language cookie using JavaScript.