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.
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.
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";
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 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"
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=/;";
| 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. |
document.cookie.expires to the past.path=/ if you want the cookie to be accessible
sitewide.