Cookies are small pieces of data stored on a user’s browser by websites. They help track user preferences, login sessions, and other information. In this guide, we’ll explore how to set cookies using JavaScript, including various scenarios and best practices.
What is a Cookie?
A cookie is a small text file stored on the user’s device. It contains key-value pairs that websites use to remember user preferences, authentication status, and more.
Syntax for Setting a Cookie
The document.cookie
property is used to set cookies in JavaScript. The syntax is:
// Basic Syntax
document.cookie = "name=value; path=/; domain=example.com; secure; httponly; samesite=lax";
Parameters
- name=value: The name and value of the cookie.
- path: Restricts the cookie to a specific path (default is the current path).
- domain: Restricts the cookie to a specific domain.
- secure: Ensures the cookie is only sent over HTTPS.
- httponly: Prevents JavaScript from accessing the cookie, reducing XSS risks.
- samesite: Controls how cookies are sent with cross-site requests (e.g.,
Lax
,Strict
,None
).
Setting a Basic Cookie
Here’s how to set a basic cookie:
// Set a cookie
function setCookie(name, value) {
document.cookie = `${name}=${value}`;
}
// Usage
setCookie('username', 'JohnDoe');
This cookie will expire when the browser is closed and is accessible to all paths and domains.
Setting a Cookie with Expiration
To make a cookie persistent, set an expiration date:
// Set a cookie with expiration
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = `expires=${date.toUTCString()}`;
document.cookie = `${name}=${value}; ${expires}; path=/`;
}
// Usage
setCookie('username', 'JohnDoe', 30); // Expires in 30 days
Setting a Cookie with Path
Restrict a cookie to a specific path:
// Set a cookie with path
function setCookie(name, value, path) {
document.cookie = `${name}=${value}; path=${path}`;
}
// Usage
setCookie('theme', 'dark', '/dashboard'); // Only accessible on /dashboard
Setting a Cookie with Domain
Restrict a cookie to a specific domain:
// Set a cookie with domain
function setCookie(name, value, domain) {
document.cookie = `${name}=${value}; domain=${domain}`;
}
// Usage
setCookie('user_id', '12345', 'example.com'); // Only accessible on example.com
Setting a Secure Cookie
Ensure cookies are only sent over HTTPS:
// Set a secure cookie
function setCookie(name, value) {
document.cookie = `${name}=${value}; secure`;
}
// Usage
setCookie('auth_token', 'abc123'); // Only sent over HTTPS
Setting an HttpOnly Cookie
Prevent JavaScript from accessing the cookie:
// Set an HttpOnly cookie
function setCookie(name, value) {
document.cookie = `${name}=${value}; httponly`;
}
// Usage
setCookie('session_id', 'xyz789'); // Not accessible via JavaScript
Setting a SameSite Cookie
Control how cookies are sent with cross-site requests:
// Set a SameSite cookie
function setCookie(name, value, sameSite) {
document.cookie = `${name}=${value}; samesite=${sameSite}`;
}
// Usage
setCookie('cart_id', '5678', 'lax'); // Lax SameSite policy
Best Practices
- Keep Data Small: Cookies are transmitted with every request, so keep them concise.
- Use Secure and HttpOnly Flags: Enhance security by setting
secure
andhttponly
flags. - Set Proper Domains and Paths: Restrict cookies to relevant domains and paths to prevent conflicts.
- Avoid Sensitive Data: Never store sensitive information like passwords in cookies.
- Use JSON for Complex Data: Store complex data as JSON strings.
Using JSON with Cookies
Store and retrieve complex data using JSON:
// Set a JSON cookie
function setCookie(name, value) {
const jsonValue = JSON.stringify(value);
document.cookie = `${name}=${jsonValue}`;
}
// Get a JSON cookie
function getCookie(name) {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(name + '=')) {
const value = cookie.split('=')[1];
return JSON.parse(value);
}
}
return null;
}
// Usage
const user = { name: 'John', age: 30 };
setCookie('user', user);
const retrievedUser = getCookie('user');
console.log(retrievedUser); // { name: 'John', age: 30 }
Frequently Asked Questions
1. How long do cookies last?
- Session Cookies: Deleted when the browser is closed (no expiration date).
- Persistent Cookies: Last until their expiration date.
2. Are cookies secure?
- Cookies can be secure if you set the
secure
andhttponly
flags. They’re transmitted over HTTPS and inaccessible via JavaScript.
3. Can I store JSON in cookies?
- Yes, you can store JSON strings in cookies. Always parse them when retrieving.
4. How do I delete a cookie?
- Set the cookie’s expiration date to a past date:
function deleteCookie(name) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/`;
}
5. What are the alternatives to cookies?
- Local Storage: Persistent storage without an expiration date.
- Session Storage: Similar to local storage but cleared when the session ends.
- IndexedDB: For storing structured data.
Conclusion
Cookies are essential for tracking user sessions and preferences. By following best practices and understanding cookie attributes, you can enhance security and functionality in your web applications. Always test your cookie implementation across different browsers and devices to ensure compatibility.