DEV Community

Muhaymin Bin Mehmood
Muhaymin Bin Mehmood

Posted on

How to Set, Read, and Delete Cookies in JavaScript πŸͺ

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=/;";
Enter fullscreen mode Exit fullscreen mode

βœ… With expiration:

document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/;";
Enter fullscreen mode Exit fullscreen mode

πŸ” Read a Cookie

console.log(document.cookie); 
// returns: "username=JohnDoe; theme=dark"
Enter fullscreen mode Exit fullscreen mode

To extract a value, you’ll need a helper:

function getCookie(name) {
  return document.cookie
    .split('; ')
    .find(row => row.startsWith(name + '='))
    ?.split('=')[1];
}
Enter fullscreen mode Exit fullscreen mode

❌ Delete a Cookie

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Enter fullscreen mode Exit fullscreen mode

Yep β€” just set the expiration date to the past.

Want the Full Guide with Examples and Security Tips?

I’ve covered everything β€” including:

  1. js set cookie and javascript set cookie best practices
  2. A reusable helper for reading cookies
  3. How to delete cookie js reliably
  4. Cookie flags (HttpOnly, Secure, SameSite)
  5. 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)