Client-Side Storage in Javascript
Cookies are small pieces of data stored in the user's browser by websites. They are primarily used to remember users and their preferences, authentication tokens, and other data needed for the website to function properly. Unlike localStorage and sessionStorage, cookies have a size limit of 4KB per cookie and an expiration date that can be set by the website.
document.cookie = "key=value; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
This code sets a cookie named 'key' with the value 'value'. It also sets an expiration date for the cookie to be valid until December 18, 2025, and specifies the path where the cookie is valid.
const cookies = document.cookie;
This code retrieves all cookies stored for the current website and stores them in the variable 'cookies'. Cookies are returned as a string containing key-value pairs separated by semicolons.
document.cookie = "key=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
This code removes the cookie named 'key' by setting its expiration date to a past time, effectively invalidating the cookie.
Cookies have various use cases in web applications:
Cookies come with several limitations: