HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Cookies

Cookies are small pieces of data stored in text files on your computer. They are used to bridge the communication gap between the browser and the server, allowing websites to "remember" information about a visitor (like a username or a theme preference) even after the page is closed or refreshed.


Interactive Cookie Manager

Test how cookies work in your browser using this tool. Note: Cookies might not work if you are viewing this file via 'file://' protocol; use a local server like Laragon.


Creating a Cookie

JavaScript can create and update cookies by using the document.cookie property. A cookie is saved as a key-value pair.

// Create a simple cookie
document.cookie = "username=Hridoy Datta";

Adding an Expiry Date

By default, a cookie is deleted when the browser is closed. To make it last longer, you must add an expiry date (in UTC time) using the expires parameter.

// Cookie expires on a specific date
document.cookie = "username=RedoHub; expires=Thu, 18 Dec 2026 12:00:00 UTC";

// You can also specify the path (default is current page)
document.cookie = "username=RedoHub; expires=...; path=/";

Reading Cookies

Reading document.cookie will return all cookies for the current domain in one single string, separated by semicolons.

let allCookies = document.cookie;
console.log(allCookies); 
// Output: "username=RedoHub; theme=dark"
Note: Browsers do not allow you to read just one specific cookie directly. You usually have to write a small helper function to split the string and find the key you need.

Deleting a Cookie

To delete a cookie, you don't need a special function. You simply set the same cookie name again but give it an expiry date that has already passed.

// Deleting a cookie by setting a past date
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Cookie Parameters Table

Parameter Description
expires Sets when the cookie should be deleted. (Format: UTC string)
path Defines which pages the cookie belongs to. Use / for entire site.
domain Defines the domain the cookie belongs to.
Secure Ensures the cookie is only sent over HTTPS.
Tip: For modern web development, consider using LocalStorage or SessionStorage if you don't need the server to read the data. They are easier to use and more powerful.

Key Points to Remember

  • Cookies are stored as **strings** inside document.cookie.
  • The maximum size of a cookie is typically **4KB**.
  • A single website can store many cookies, but browsers limit the total number.
  • Updating a cookie is simply overwriting it with the same name.
  • To delete, set expires to the past.
  • Always specify a path=/ if you want the cookie to be accessible sitewide.