Skip to content

How to Manage Cookies with JavaScript: Complete 2025 Guide

How to Manage Cookies with JavaScript: Complete 2025 Guide

Cookie management remains a fundamental part of modern web development, especially for personalizing the user experience and complying with privacy regulations. In 2025, with the constant evolution of GDPR and ePrivacy requirements, mastering cookie management techniques in JavaScript has become essential for every developer. This guide presents the most effective methods to create, read, and delete cookies while following current best practices.

The basics of cookies in JavaScript

Cookies are small text files stored by the browser that retain information between sessions. They play a crucial role in many web features like authentication, user preferences, or analytics tracking.

Anatomy of a cookie

A cookie consists of several key elements:

  • Name and value: the cookie's identifier and the data it contains
  • Lifetime: defined by an expiration date
  • Domain and path: determines where the cookie is available
  • Security attributes: like HttpOnly, Secure, or SameSite

Creating and modifying cookies in JavaScript

The traditional method to create a cookie is to manipulate the document.cookie property. Here's how to create a reusable function to set cookies precisely:

function setCookie(cname, cvalue, exminutes) {
  var d = new Date();
  d.setTime(d.getTime() + (exminutes * 60 * 1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

This function takes three parameters: the cookie name, its value, and its lifetime in minutes. It uses the Date object to accurately calculate the expiration time, then assembles the string that defines the cookie.

Parameter Description Example
cname Cookie name "userPreference"
cvalue Value to store "darkMode"
exminutes Lifetime in minutes 60 (for 1 hour)

Usage example

// Create a cookie that expires in 30 minutes
setCookie("userSession", "active", 30);

// Create a cookie that expires in 24 hours
setCookie("themePreference", "dark", 1440);

Reading cookies with JavaScript

Reading cookies requires parsing the document.cookie string to extract the specific value you're looking for. Here's a robust reading function that correctly handles cookies containing special characters:

function getCookie(cname) {
  var name = cname + "=";
  try {
    var decodedCookie = decodeURIComponent(document.cookie);
  } catch(e) {
    var decodedCookie = document.cookie;
  }
  var ca = decodedCookie.split(";");
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

This function includes error handling with a try/catch block to avoid issues with decoding cookies that contain non-URI characters. It then iterates through all available cookies to find the one matching the requested name.

Checking if a cookie exists

To check if a cookie exists and contains a specific value, you can use the getCookie function as follows:

// Check if the user has an active session
var userSession = getCookie("userSession");
if (userSession === "active") {
  // The user has an active session
} else {
  // Redirect to the login page
}

Deleting cookies in JavaScript

To delete a cookie, simply redefine it with an expiration date in the past. Here's an effective deletion function:

function deleteCookie(cname) {
  document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

This method sets the expiration date to January 1, 1970, which forces the browser to consider the cookie expired and delete it immediately.

Cookie management and GDPR compliance in 2025

In 2025, compliance with privacy regulations like GDPR is stricter than ever. Legal requirements in France mandate obtaining explicit consent before storing non-essential cookies.

Implementing a consent system

A consent management platform (CMP) lets users choose which types of cookies they accept. Here's a simplified implementation example:

function checkCookieConsent() {
  var consent = getCookie("cookieConsent");
  if (consent !== "accepted") {
    // Show the consent banner
    showConsentBanner();
  } else {
    // Load analytics scripts and other cookies
    loadAnalytics();
  }
}

function acceptCookies() {
  setCookie("cookieConsent", "accepted", 43200); // 30 days
  hideConsentBanner();
  loadAnalytics();
}

function rejectCookies() {
  setCookie("cookieConsent", "rejected", 43200); // 30 days
  hideConsentBanner();
  // Do not load analytics scripts
}

Best practices for cookie management in 2025

For optimal cookie management in 2025, follow these essential recommendations:

  • Use the SameSite attribute to protect against CSRF attacks
  • Enable the Secure attribute to restrict cookies to HTTPS connections
  • Avoid storing sensitive information in cookies
  • Prefer session cookies for temporary data
  • Clearly document cookie usage in your privacy policy
  • Use specialized libraries for complex projects

Secure implementation example

function setSecureCookie(cname, cvalue, exminutes) {
  var d = new Date();
  d.setTime(d.getTime() + (exminutes * 60 * 1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;Secure;SameSite=Strict";
}

Alternatives to traditional cookies

If cookies don't suit your use case, several modern alternatives exist:

Web Storage API

The Web Storage API offers two storage mechanisms with a simpler interface than cookies:

// localStorage (persistent)
localStorage.setItem('theme', 'dark');
var theme = localStorage.getItem('theme');

// sessionStorage (temporary)
sessionStorage.setItem('lastPage', '/dashboard');
var lastPage = sessionStorage.getItem('lastPage');

IndexedDB

For more complex or larger data, IndexedDB offers an advanced storage solution:

// Simplified example of using IndexedDB
var request = indexedDB.open("myDatabase", 1);

request.onupgradeneeded = function(event) {
  var db = event.target.result;
  var objectStore = db.createObjectStore("settings", { keyPath: "id" });
};

Integration with modern JavaScript libraries

For projects using frameworks like React, Vue.js, or Angular, specific approaches can simplify cookie management:

React with js-cookie

import Cookies from 'js-cookie';

// Set a cookie
Cookies.set('name', 'value', { expires: 7, secure: true });

// Read a cookie
const value = Cookies.get('name');

// Delete a cookie
Cookies.remove('name');

Vue.js with vue-cookies

// In the Vue component
export default {
  mounted() {
    this.$cookies.set('name', 'value', '1d');
    const value = this.$cookies.get('name');
  }
}

Conclusion

Effective cookie management in JavaScript remains a fundamental skill for web developers in 2025. By following the best practices in this guide, you'll be able to implement robust, secure, and regulation-compliant solutions.

To go further in optimizing your development workflow, discover how Roboto.fr can help you generate optimized JavaScript code and custom cookie management solutions. Sign up for free at Roboto to explore all the features available for modern web developers.

Additional illustration on javascript cookie management