Small pieces of data stored in the browser that websites use to remember information about users.
Cookies are small text files stored in your browser by websites. They remember information about you - login status, preferences, shopping cart items - so the website recognizes you on your next visit.
Think of cookies like a loyalty card. The store gives you a card with your ID. Next time you visit, they scan your card and know who you are and what you like.
All automatic. Happens in milliseconds.
Simple key-value pairs with some settings like expiration dates and security flags.
Authentication: Remember you are logged in
Shopping Cart: Keep items in cart between pages
Preferences: Remember dark mode, language, timezone
Analytics: Track which pages you visit
Ads: Target ads based on browsing history
(Node.js): Use response methods to set cookies with options like maxAge, httpOnly, and secure flags.
Client-Side (JavaScript): Use document.cookie to set cookies directly in the browser.
Server-Side: Access cookies from the request object.
Client-Side: Read from document.cookie property.
expires / max-age: When cookie expires
domain: Which domain can read the cookie
path: Which URLs can access the cookie
secure: Only send over HTTPS
httpOnly: JavaScript cannot access (prevents XSS attacks)
SameSite: Control cross-site cookie behavior
Session Cookies: Deleted when browser closes - no expiration set.
Persistent Cookies: Stored for specified time - expiration date set explicitly.
XSS Attacks: Malicious scripts steal cookies
CSRF Attacks: Trick browser into sending cookies to wrong site
Cookie Theft: Attacker intercepts cookies
GDPR and other laws require cookie consent for tracking. You have seen cookie banners on every website. Required by law in EU and many other regions.
Cookies:
localStorage:
Use cookies for authentication. Use localStorage for larger client-side data.
First-Party: Set by the site you visit
Third-Party: Set by other domains (ads, analytics)
Browsers increasingly block third-party cookies for privacy.
JavaScript libraries like js-cookie make working with cookies much simpler than parsing document.cookie manually.
Cookies are essential for web authentication and user experience. They remember who you are across page loads and visits.
Understand cookies, use them securely, and respect user privacy. Every web developer works with cookies constantly.