Js Cookies in JavaScript
? JavaScript Cookies
What are Cookies?
Small pieces of data stored in the user's browser.
Used to remember information between page reloads or visits (e.g., user sessions, preferences).
How to Set a Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";Format:
"key=value; expires=DATE; path=PATH; domain=DOMAIN; secure"expires— sets expiration date. If omitted, cookie lasts until browser closes.path— limits cookie to a specific path (default is current path).secure— cookie sent only over HTTPS.
How to Get Cookies
console.log(document.cookie);// Output: "username=JohnDoe; theme=dark"Returns all cookies as a single string separated by
;.You need to parse this string to get individual cookies.
Example function to get a cookie by name:
function getCookie(name) { const cookies = document.cookie.split('; '); for (const cookie of cookies) { const [key, value] = cookie.split('='); if (key === name) return value; } return null;}console.log(getCookie("username")); // JohnDoeHow to Delete a Cookie
Set the cookie with a past expiration date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";Important Notes
Cookies size limit ~4KB.
Cookies are sent with every HTTP request to the domain.
For complex data, consider
localStorageorsessionStorage.
Want me to show you how to manage cookies with a ready-to-use JS utility function or explain differences between cookies, localStorage, and sessionStorage?