Cookies
This lesson explains Cookies with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.
HTML5 Cookies API Overview
Cookies are small pieces of data stored by the browser and sent to the
server with every HTTP request for the same domain. Cookies are widely
used for authentication, session management, user preferences,
personalization, analytics, shopping carts, and remembering login
information.
Unlike Local Storage and Session Storage, cookies are automatically
included in HTTP requests, making them useful for maintaining server-side
sessions. Modern browsers also provide security attributes such as
Secure, HttpOnly, and
SameSite to help protect user data.
| Feature | Description |
| Storage Type | Small key-value pairs |
| JavaScript API | document.cookie |
| Maximum Size | Approximately 4 KB per cookie |
| Expiration | Session or persistent |
| Automatically Sent to Server | Yes |
| Common Uses | Authentication, sessions, preferences, analytics |
Cookie Syntax
// Create a cookie
document.cookie =
"username=John";
// Create a cookie with expiration
document.cookie =
"theme=dark; expires=Tue, 31 Dec 2026 23:59:59 UTC";
// Cookie with additional attributes
document.cookie =
"language=en; path=/; Secure; SameSite=Lax";
Cookies consist of a name, value, and optional attributes that control
expiration, security, domain, and accessibility.
Cookie Attributes
| Attribute | Description | Example |
| expires | Sets cookie expiration date. | expires=Tue, 31 Dec 2026 23:59:59 UTC |
| max-age | Expiration in seconds. | max-age=86400 |
| path | Accessible path. | path=/ |
| domain | Accessible domain. | domain=example.com |
| Secure | Sent only over HTTPS. | Secure |
| HttpOnly | Cannot be accessed from JavaScript. | Server Only |
| SameSite | Controls cross-site cookie behavior. | SameSite=Lax |
Create a Cookie
// Store user preference
document.cookie =
"theme=dark";
// Store preferred language
document.cookie =
"language=en-US";
Without an expiration date, the cookie becomes a session cookie and is
removed when the browser closes.
Create a Persistent Cookie
// Cookie valid for one year
const expires =
new Date(
Date.now() + 365 * 24 * 60 * 60 * 1000
).toUTCString();
document.cookie =
"theme=dark; expires=" +
expires +
"; path=/";
Persistent cookies remain available until the expiration date or until
they are manually deleted.
Read Cookies
// Read all cookies
console.log(document.cookie);
// Find one cookie
function getCookie(name) {
const cookies =
document.cookie.split("; ");
for (const cookie of cookies) {
const parts =
cookie.split("=");
if (parts[0] === name) {
return parts[1];
}
}
return null;
}
console.log(
getCookie("theme")
);
The browser stores cookies as a semicolon-separated string. Developers
often create helper functions to simplify reading individual cookies.
Update a Cookie
// Updating simply overwrites
// the previous cookie
document.cookie =
"theme=light; path=/";
Cookies are updated by creating another cookie with the same name and
path.
Delete a Cookie
// Delete cookie
document.cookie =
"theme=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Cookies cannot be deleted directly. Instead, they are expired by setting
an expiration date in the past.
Cookies vs Local Storage vs Session Storage
| Feature | Cookies | Local Storage | Session Storage |
| Capacity | ~4 KB | 5–10 MB | 5–10 MB |
| Sent to Server | Yes | No | No |
| Expiration | Configurable | Until deleted | Tab closes |
| Access | Browser & Server | Browser only | Browser only |
| Best Use | Sessions & Authentication | User Preferences | Temporary Data |
Common Cookie Use Cases
| Application | Purpose |
| User Login | Maintain authenticated sessions. |
| Shopping Cart | Remember cart items. |
| Theme Preference | Store dark/light mode. |
| Language Preference | Remember selected language. |
| Analytics | Track anonymous visitors. |
| Remember Me | Persist login information. |
| User Preferences | Save UI settings. |
Cookie Security Best Practices
| Recommendation | Reason |
| Use Secure | Send cookies only over HTTPS. |
| Use HttpOnly | Prevent JavaScript access to authentication cookies. |
| Use SameSite=Lax or Strict | Reduce CSRF attacks. |
| Keep Cookies Small | Improve request performance. |
| Never Store Passwords | Protect sensitive information. |
| Encrypt Sensitive Values | Reduce exposure if cookies are compromised. |
Common Cookie Mistakes
- Storing passwords or confidential information inside cookies.
- Not using Secure for HTTPS websites.
- Ignoring SameSite protection.
- Using cookies for large amounts of data.
- Forgetting to set expiration dates.
- Not validating cookie values on the server.
- Ignoring HttpOnly for authentication cookies.
- Reading cookies repeatedly instead of caching values.
Key Takeaways
- Cookies store small key-value data shared between browser and server.
document.cookie is used to create and read cookies in JavaScript. - Cookies automatically travel with HTTP requests.
- Use cookies mainly for authentication and session management.
- Prefer Local Storage for large client-side preferences.
- Always use Secure, HttpOnly, and SameSite whenever appropriate.
Pro Tip
Store authentication tokens in secure, HttpOnly cookies
whenever possible instead of Local Storage. This greatly reduces the risk
of token theft through Cross-Site Scripting (XSS) attacks.