JavaScript
/Intermediate
Cookies
Definition
Small pieces of data stored on the user's computer by the web browser while browsing a website. Unlike LocalStorage, cookies are automatically sent to the server with every HTTP request.
Explain Like I'm New
Cookies are like a digital ID badge. Once the bouncer (server) gives you one, you automatically wear it on your shirt. Every time you ask for a drink (make a network request), the bartender instantly sees the badge and knows who you are without you having to say anything.
Real World Example
Storing an authentication session ID or a JWT. The server sets an `HttpOnly` cookie, and the browser automatically attaches it to all future API calls to prove the user is logged in.
Common Use Cases
- •Session management (Logins)
- •Tracking and analytics
- •Personalization
Terminal Output
bash / terminal
// Reading cookies in JS (WARNING: Returns a giant, unparsed string)
console.log(document.cookie); // "theme=dark; userId=123"
// Writing a cookie in JS (Not recommended for Auth! Use server-side HttpOnly)
document.cookie = "theme=dark; max-age=3600; path=/";
// A much better modern approach for reading cookies is the new Cookie Store API:
// (Only available in modern Chrome/Edge)
/*
const themeCookie = await cookieStore.get('theme');
console.log(themeCookie.value);
*/
Interview Questions
basic
- What is the maximum size of a cookie?
intermediate
- What is the difference between `HttpOnly` and `Secure` flags on a cookie?
advanced
- How do cookies differ from LocalStorage in terms of network overhead?