HTTP Cookies


HTTP Cookies are small pieces of data that a web server sends to a client’s browser. The browser then stores these cookies and sends them back to the server with every subsequent request to the same domain. This mechanism allows websites to “remember” information about the user across multiple requests or even across multiple browsing sessions.

How Cookies Work:

  1. Server Sends a Set-Cookie Header: When a user interacts with a website, the server can include a Set-Cookie header in the HTTP response. This header contains the cookie’s data.

  2. Browser Stores the Cookie: The browser receives the Set-Cookie header and stores the cookie locally.

  3. Browser Sends Cookies with Requests: For every subsequent request to the same domain, the browser automatically includes all applicable cookies in the Cookie header of the HTTP request.

  4. Server Accesses Cookies: The server can then access the cookies sent by the browser and use the stored information.

Example in JavaScript (Setting a Cookie):

// Set a cookie named "username" with the value "john_doe"
// It expires after 30 days
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + (30 * 24 * 60 * 60 * 1000));
document.cookie = `username=john_doe; expires=${expirationDate.toUTCString()}; path=/`;


// Setting a cookie with additional attributes
document.cookie = "theme=dark; path=/; SameSite=Strict; Secure"; 

Explanation of Attributes:

Uses of Cookies:

Cookie Limitations:

By understanding how HTTP cookies work and their associated attributes, developers can effectively utilize them for various functionalities while keeping security and privacy considerations in mind.