Managing cookies is something every web developer runs into β whether you're tracking sessions, saving preferences, or handling user auth.
But the document.cookie
API? It's surprisingly low-level, and a bit of a mess if you're not careful.
So I put together a full guide that explains how to set, read, and delete cookies using plain JavaScript, with clean examples and a working demo.
Hereβs a quick taste πͺπ
β Set a Cookie in JavaScript
document.cookie = "username=JohnDoe; path=/;";
β With expiration:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/;";
π Read a Cookie
console.log(document.cookie);
// returns: "username=JohnDoe; theme=dark"
To extract a value, youβll need a helper:
function getCookie(name) {
return document.cookie
.split('; ')
.find(row => row.startsWith(name + '='))
?.split('=')[1];
}
β Delete a Cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Yep β just set the expiration date to the past.
Want the Full Guide with Examples and Security Tips?
Iβve covered everything β including:
- js set cookie and javascript set cookie best practices
- A reusable helper for reading cookies
- How to delete cookie js reliably
- Cookie flags (HttpOnly, Secure, SameSite)
- A complete working demo
π Read it here:
π How to Read, Write, and Delete Cookies in JavaScript
Let me know what cookie issues you've run into β I'm happy to help or expand the article further!
Top comments (0)