What are Cookies in JavaScript
Illustration showing how cookies work in JavaScript for storing user data in the browser
Cookies are small pieces of data (key-value pairs) that are stored on the user's browser and can be used by websites to remember information between page loads or sessions. JavaScript can create, read, and delete cookies associated with the current web page.
To store user preferences
To track user sessions (e.g., login sessions)
To implement simple data persistence across visits
document.cookie = "username=JohnDoe";
You can also add attributes like expiration, path, etc.:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
console.log(document.cookie);
// Output: "username=JohnDoe; theme=dark"
You will get all cookies in a single string separated by ;
.
To delete a cookie, set its expiration date to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Cookies are limited to about 4KB of data per cookie.
Cookies are sent to the server with every HTTP request.
Cookies are domain- and path-specific.
Cookies can be made secure and HTTP-only, but that must be set from the server side, not JavaScript.
// Set cookie
document.cookie = "theme=dark; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
// Read cookie
console.log(document.cookie);
localStorage
(persistent data storage)
sessionStorage
(session-only storage)
These are often preferred for client-side data that doesn't need to be sent to the server.