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.


 Create a Cookie

This creates a cookie named username with value Vipul.


 Set Cookie with Expiration


 

  • expires – Sets expiration date

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


 Read Cookies

Get a specific cookie


 


 Delete a Cookie

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


 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.


 Example: Cookie Storage for User Theme


 


 Cookies vs Web Storage

FeatureCookiesLocalStorageSessionStorage
Storage Size~4KB~5MB~5MB
ExpirationCan set expiryUntil manually clearedUntil tab closed
Accessible by server? Yes No No
Used forAuthentication, small dataLarge client-side dataTemporary 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...