Cookies

Learn how cookies work in JavaScript, from setting, reading, updating, and deleting cookies to understanding their use cases and limitations.

Loading...
Cookies

We’ve covered a lot already, now it’s time for cookies!! 🍪

JavaScript Cookies

But not the kind you eat (sorry!).

I'm talking about JavaScript Cookies.

In JavaScript, Cookies are small pieces of data stored in your browser to remember information across sessions.

They're mainly used for things like:

  • Remembering login sessions
  • Tracking user preferences
  • Analytics and personalization

What Are Cookies?

Cookies are tiny bits of text your browser saves when you visit a website. Each cookie is a small key-value pair associated with a web page.

Unlike localStorage or sessionStorage, cookies:

  • Are automatically sent to the server with every HTTP request
  • Have size and quantity limits (~4KB per cookie, ~20 cookies per domain)
  • Can have expiration times and other options like path or security

Creating Cookies in JavaScript

document.cookie = "username=Shefali";

This sets a cookie named username with the value Shefali.

Setting Expiry

document.cookie = "theme=dark; expires=Fri, 31 Dec 2025 23:59:59 GMT";

The cookie will expire after the given date. If you don’t set an expiration, it becomes a session cookie and is removed when the browser closes.

Setting Path

document.cookie = "loggedIn=true; path=/";

The path=/ means the cookie is accessible on all pages of the site.


Reading Cookies

To get the stored cookies:

console.log(document.cookie);

This returns all cookies as a single string:

"username=Shefali; theme=dark; loggedIn=true"

To extract individual values, you’ll need to split the string:

// Splits the cookie string into individual "key=value" parts
const cookies = document.cookie.split("; ");
 
// Finds the cookie that starts with "username="
const user = cookies.find((cookie) => cookie.startsWith("username="));
 
// Gets the value after the "=" sign
const username = user?.split("=")[1];
 
console.log(username); // Output: Shefali

To update a cookie, just reassign it:

document.cookie = "username=LearnifyUser";

It overwrites the previous username cookie.


To delete a cookie, set its expiry to a past date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Limitations of Cookies

  • Limited size (~4KB per cookie).
  • Not suitable for storing complex or large data.
  • Sent with every HTTP request, it can impact performance.
  • Not secure unless used with Secure and HttpOnly flags (set via server).

Support my work!