JavaScript Cookies

JavaScript Tutorial

JavaScript Cookies

In JavaScript Cookies is a small piece of data stored in the browser.
Cookies are often used to:

Unlike LocalStorage/SessionStorage, cookies are sent to the server with every HTTP request.


1️⃣ Create a Cookie


This creates a cookie named username with value Vipul.


2️⃣ Set Cookie with Expiration


 

  • expires – Sets expiration date

  • path=/ – Makes cookie accessible on the entire website


3️⃣ Read Cookies


Get a specific cookie


 


4️⃣ Delete a Cookie

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



5️⃣ Secure and HttpOnly Cookies

  • Secure – Only sent over HTTPS

  • HttpOnly – Not accessible via JavaScript (for security)

Example:


Note: HttpOnly cookies cannot be created via JavaScript. They must be set by the server.


6️⃣ Example: Cookie Storage for User Theme


 


7️⃣ Cookies vs Web Storage

Feature Cookies LocalStorage SessionStorage
Storage Size ~4KB ~5MB ~5MB
Expiration Can set expiry Until manually cleared Until tab closed
Accessible by server? ✔ Yes ❌ No ❌ No
Used for Authentication, small data Large client-side data Temporary session data

Summary

  • Use cookies for server communication (sessions, login)

  • Use LocalStorage/SessionStorage for larger client-side data

  • Always manage expiration dates

  • Avoid storing sensitive data in client-accessible cookies

You may also like...