What are Cookies in JavaScript

6/29/2025
All Articles

Illustration showing how cookies work in JavaScript for storing user data in the browser

 What are Cookies in JavaScript

 What are Cookies in JavaScript?

Cookies are small pieces of data (key-value pairs) that are stored on the user's browser and can be used by websites to remember information between page loads or sessions. JavaScript can create, read, and delete cookies associated with the current web page.


 Why Use Cookies?

  • To store user preferences

  • To track user sessions (e.g., login sessions)

  • To implement simple data persistence across visits


🛠️ How to Use Cookies in JavaScript

✅ Set a Cookie

document.cookie = "username=JohnDoe";

You can also add attributes like expiration, path, etc.:

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

📖 Read Cookies

console.log(document.cookie);
// Output: "username=JohnDoe; theme=dark"

You will get all cookies in a single string separated by ; .


❌ Delete a Cookie

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

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

🔒 Important Notes

  • Cookies are limited to about 4KB of data per cookie.

  • Cookies are sent to the server with every HTTP request.

  • Cookies are domain- and path-specific.

  • Cookies can be made secure and HTTP-only, but that must be set from the server side, not JavaScript.


✍️ Example

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

// Read cookie
console.log(document.cookie);

Alternatives to Cookies

  • localStorage (persistent data storage)

  • sessionStorage (session-only storage)

These are often preferred for client-side data that doesn't need to be sent to the server.

Article