Cookies are small notes that browser automatically sends to server with every request. Used for authentication, personalization and storing user settings. 🍪
// Setting cookie
document.cookie = 'username=John; path=/; expires=Fri, 31 Dec 2024 23:59:59 GMT';
// Reading cookie
console.log(document.cookie); // 'username=John'Cookies are like notes you attach to a letter every time you write to a friend. Server can read these notes and remember who you are! 📝
Cookies are small pieces of data (up to 4 KB) that:
// Simple cookie
document.cookie = 'theme=dark';// ✅ Save auth token
document.cookie = 'token=abc123; path=/; secure';
// Server will see this token in every request// ✅ Remember user language
document.cookie = 'language=en; path=/; max-age=31536000';
// Site will know language on next visit// ✅ Save interface settings
document.cookie = 'fontSize=large; path=/; expires=Fri, 31 Dec 2024 23:59:59 GMT';// Basic setting
document.cookie = 'name=value';
// With parameters
document.cookie = 'username=John; path=/; expires=Fri, 31 Dec 2024 23:59:59 GMT; secure';// Read all cookies
console.log(document.cookie); // 'username=John; theme=dark'
// Cookies come as string, need to parse// ❌ Bad — cookies sent with every request
document.cookie = 'bigData=very_large_data'; // Slows site!
// ✅ Better — use localStorage
localStorage.setItem('bigData', 'very_large_data');// ❌ Problem — cookie without expiration deleted when browser closes
document.cookie = 'temp=data';
// ✅ Good — set expiration
document.cookie = 'temp=data; max-age=3600'; // For one hour// ❌ Unsafe — cookie accessible through JavaScript
document.cookie = 'token=abc123';
// ✅ Safer — HttpOnly cookie set by server
// Set-Cookie: token=abc123; HttpOnly; Secure// ✅ Authentication (tokens, sessions)
// ✅ Personalization (language, theme)
// ✅ Tracking (analytics, advertising)// ❌ Large data (4 KB limit)
// ❌ Frequent changes (loads requests)
// ❌ Confidential data (visible in requests)Understanding Cookies helps store user data correctly and work with authentication! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪