JavaScript Cookies

JavaScript Cookies
In JavaScript Cookies is a small piece of data stored in the browser.
Cookies are often used to:
Save user preferences
Store login information
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 datepath=/– 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:
HttpOnlycookies cannot be created via JavaScript. They must be set by the server.
Example: Cookie Storage for User Theme
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
