Follow This Blog For more... 😊

Cookies in JavaScript

Thumbnail of blog post "Cookie in Javascript"

Cookies in JavaScript: A Complete Guide!

Cookies are small pieces of data stored on the client’s browser, used to store information about user sessions, preferences, and activities. In JavaScript, cookies can be created, read, and deleted to manage user-specific data effectively.

This post provides a detailed explanation of cookies in JavaScript, covering what cookies are, their structure, use cases, how to work with them, and best practices.


What Are Cookies?

Cookies are key-value pairs stored in the browser and sent to the server with every HTTP request. They allow websites to:

  • Store user preferences (e.g., theme selection, language).
  • Maintain sessions (e.g., login state).
  • Track user activities (e.g., shopping cart contents, analytics).

How Cookies Work

  1. Storage: Cookies are stored as text files in the user's browser.
  2. Transmission: Cookies are automatically included in HTTP headers for each request to the server.
  3. Lifetime: Cookies can be:
    • Session Cookies: Deleted when the browser is closed.
    • Persistent Cookies: Have a specific expiration date and survive browser restarts.
  4. Scope:
    • Domain: Defines which domain can access the cookie.
    • Path: Limits access to specific paths on the server.

Structure of a Cookie

A cookie has the following format:

key=value; expires=date; path=URL; domain=domainName; secure; HttpOnly

Key Attributes

  • key=value: The name and value of the cookie.
  • expires: Sets the expiration date (default is session-based if omitted).
  • path: Specifies the URL path for which the cookie is valid.
  • domain: Defines the domain the cookie applies to.
  • secure: Ensures the cookie is transmitted over HTTPS only.
  • HttpOnly: Prevents client-side JavaScript access for security.

Working with Cookies in JavaScript

1. Setting a Cookie

You can set a cookie using document.cookie.

Example

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
  • username=JohnDoe: The key-value pair for the cookie.
  • expires: Sets the expiration date.
  • path=/: Makes the cookie accessible across the entire domain.

JavaScript Function to Set a Cookie

function setCookie(name, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  const expires = "expires=" + date.toUTCString();
  document.cookie = `${name}=${value}; expires=${expires}; path=/`;
}

setCookie("theme", "dark", 7); // Creates a cookie named "theme" that expires in 7 days.

2. Reading a Cookie

To retrieve cookies, use document.cookie. It returns all cookies as a single string, separated by ;.

Example

console.log(document.cookie);
// Output: "username=JohnDoe; theme=dark"

JavaScript Function to Get a Cookie by Name

function getCookie(name) {
  const cookies = document.cookie.split("; ");
  for (let cookie of cookies) {
    const [key, value] = cookie.split("=");
    if (key === name) {
      return value;
    }
  }
  return null;
}

console.log(getCookie("username")); // Output: JohnDoe

3. Deleting a Cookie

To delete a cookie, set its expiration date to a past date.

Example

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

JavaScript Function to Delete a Cookie

function deleteCookie(name) {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
}

deleteCookie("username"); // Deletes the "username" cookie.

Examples of Cookie Use Cases

1. Storing User Preferences

Save and retrieve user settings like theme or language.

setCookie("language", "English", 30);

console.log(getCookie("language")); // Output: English

2. Implementing a Login Session

Store a session identifier to manage login states.

setCookie("session_id", "123456789", 1);

3. Tracking User Activity

Track user visits or shopping cart contents.

let visits = parseInt(getCookie("visits")) || 0;
setCookie("visits", visits + 1, 365);
console.log(`You have visited this site ${visits + 1} times.`);

Advantages of Cookies

  • Persistence: Data persists between browser sessions.
  • Automatic Transmission: Automatically sent with HTTP requests.
  • Widespread Support: Supported by all modern browsers.

Limitations of Cookies

  1. Size Restriction: Each cookie is limited to ~4KB in size.
  2. Limited Count: Browsers restrict the number of cookies per domain (usually 20-50).
  3. Security Concerns:
  • Can be intercepted if transmitted over non-secure connections (use secure).
  • Vulnerable to XSS attacks if not set with HttpOnly.

Best Practices for Cookies

  1. Set Secure Attributes:
    • Use Secure to ensure cookies are only sent over HTTPS.
    • Use HttpOnly to prevent client-side JavaScript access.
  2. Minimize Data in Cookies:
    • Store only essential information.
    • Use server-side storage for sensitive or large data.
  3. Specify Scope:
    • Set path and domain to limit cookie exposure.
  4. Encrypt Sensitive Data:
    • Use encryption libraries to secure cookie values.

Common Questions About Cookies

1. Can Cookies Be Disabled by the User?

Yes, users can disable cookies in their browser settings. It’s a good practice to handle such scenarios gracefully in your application.

2. Are Cookies Shared Across Domains?

No, cookies are domain-specific. However, subdomains can access cookies if explicitly permitted using the domain attribute.

3. Can Cookies Be Used with Third-Party APIs?

Yes, cookies can be sent with third-party requests, but cross-domain policies and security attributes must be handled carefully.


Conclusion

Cookies are a simple and powerful way to store client-side data in JavaScript. They are instrumental in session management, user tracking, and storing preferences. By understanding how to set, retrieve, and manage cookies securely, you can create efficient and user-friendly web applications.

Master cookies, and you’ll have a robust tool in your JavaScript arsenal! Happy coding!

Comments

Popular Posts