HTTP Cookies in JavaScript

Meenu Matharu
4 min readSep 9, 2024

--

HTTP Cookies in JavaScript

HTTP cookies are small pieces of data sent by a server to a user’s web browser and stored locally. They are used for various purposes, such as session management, personalisation, and tracking user behavior. Now, we will explore about its purpose, usage and management in JavaScript.

What Are HTTP Cookies?

HTTP cookies are text files with small pieces of data that can be stored on the client-side (in the user’s browser) and sent back to the server with each HTTP request. This allows the server to remember information about the user and their session.

Key Attributes of Cookies

  • Name: The name of the cookie.
  • Value: The value stored in the cookie.
  • Domain: The domain for which the cookie is valid.
  • Path: The URL path for which the cookie is valid.
  • Expires/Max-Age: The expiration date or maximum age of the cookie.
  • Secure: Indicates whether the cookie should only be transmitted over secure protocols like HTTPS.
  • When a cookie is marked as secure, it means that the cookie will only be sent to the server if the connection is secure. This helps protect the cookie from being intercepted by malicious parties.
  • HttpOnly: Indicates whether the cookie is accessible only through HTTP(S) and not via client-side scripts.
  • SameSite: Controls whether the cookie is sent with cross-site requests.

How Do Cookies Work?

When a user visits a website, the server can send a Set-Cookie header in the HTTP response. The browser then stores this cookie and sends it back to the server with each subsequent request to the same domain. This allows the server to recognize returning users and maintain state across multiple requests.

Managing Cookies with JavaScript

JavaScript provides several ways to create, read, and delete cookies. Let’s explore how to manage cookies using the document.cookie property.

Creating a Cookie

To create a cookie, you can assign a string to document.cookie in the format name=value; followed by optional attributes like expires, path, domain, and secure.

// Create a cookie named "username" with a value of "JohnDoe"
document.cookie = "username=JohnDoe";
// Create a cookie with an expiration date
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT";
// Create a cookie with a path
document.cookie = "username=JohnDoe; path=/";
// Create a secure cookie
document.cookie = "username=JohnDoe; secure";

Reading a Cookie

To read a cookie, you can access document.cookie, which returns a string containing all the cookies for the current domain. You can then parse this string to find the specific cookie you are interested in.

// Get all cookies as a single string
const allCookies = document.cookie;
console.log(allCookies);
// Function to get a specific cookie by name
function getCookie(name) {
const cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
const cookiePair = cookieArr[i].split("=");
if (name === cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
// Get the value of the "username" cookie
const username = getCookie("username");
console.log(username); // Output: JohnDoe

Deleting a Cookie

To delete a cookie, you can set its expiration date to a past date. This will instruct the browser to remove the cookie.

// Function to delete a cookie by name
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
}
// Delete the "username" cookie
deleteCookie("username");

Updating a Cookie

To update a cookie, you can simply create a new cookie with the same name. This will overwrite the existing cookie.

// Update the value of the "username" cookie
document.cookie = "username=JaneDoe";

Best Practices for Using Cookies

  • Use Secure Cookies: Always use the Secure attribute to ensure cookies are only transmitted over HTTPS.
  • HttpOnly Cookies: Use the HttpOnly attribute to prevent access to cookies via JavaScript, which can help mitigate cross-site scripting (XSS) attacks.
  • SameSite Attribute: Use the SameSite attribute to prevent cross-site request forgery (CSRF) attacks by controlling when cookies are sent.
  • Keep Cookies Small: Minimize the size of cookies to reduce the impact on network performance.
  • Limit Cookie Scope: Use the Path and Domain attributes to limit the scope of cookies to the necessary parts of your site.

Conclusion

HTTP cookies are a powerful tool for managing state and personalizing user experiences on the web. By understanding how to create, read, update, and delete cookies using JavaScript, you can effectively manage user sessions and data. Remember to follow best practices to ensure the security and efficiency of your cookies.

Feel free to explore further and experiment with cookies in your web applications to see how they can enhance the user experience. Happy coding!

--

--

Meenu Matharu
Meenu Matharu

Written by Meenu Matharu

🚀 Passionate Frontend Developer | Storyteller on a Coding Journey 🌟 Dive deep into the world of frontend technologies like HTML, CSS, JavaScript and React

No responses yet