Course contentsShow
← Web Development
Lesson 797 of 2,98214. Browser StorageFree lesson

What Are Cookies and How They Work

Understanding cookies as small text files stored by the browser, their role in state management, and the request/response cycle.

What Are Cookies and How They Work

You'll learn: How cookies store small pieces of information in your browser to help websites remember you between visits.

What Are Cookies?

Cookies are small text files that websites save on your browser. Think of them like a coat check ticket at a restaurant—when you visit a website, it hands your browser a small piece of paper (the cookie) with information written on it. The next time you visit, your browser automatically shows that ticket back to the website so it remembers who you are.

Unlike localStorage or sessionStorage (which JavaScript accesses directly), cookies are primarily designed to work with HTTP requests. Every time your browser requests a page from a server, it automatically attaches any relevant cookies to that request.

The Request/Response Cycle

Here's how cookies fit into communication between browser and server:

  1. First Visit: You visit example.com. The server sends back the webpage and a cookie (via an HTTP header).
  2. Browser Stores It: Your browser saves that cookie locally.
  3. Next Visit: You return to example.com. Your browser automatically sends the cookie back with the request.
  4. Server Remembers: The server reads the cookie and knows something about you (like that you're logged in).

Why Cookies Matter for State Management

The web is stateless by default—each request is independent. Cookies solve this by carrying information between requests. They enable:

  • Login sessions (keeping you logged in)
  • Shopping carts (remembering items)
  • User preferences (theme, language)
  • Tracking and analytics

Key Takeaway: Cookies are small text files automatically sent between browser and server with every HTTP request, enabling websites to remember information across visits and maintain state.