Lesson 27: Creating Cookies
Master the fundamentals of JavaScript cookies with interactive examples and step-by-step visualizations.
27.1 Introduction to Cookies
Cookies are small pieces of data stored in a user's browser that websites use to remember information between page requests. They enable features like user sessions, personalization, and tracking.
Key points:
- Cookies are limited to about 4KB per domain
- They are sent with every HTTP request to the domain
- Browser cookies can be viewed and managed by users
- Modern alternatives include localStorage and sessionStorage
27.2 Creating Cookies
Cookies are created using the document.cookie
property. The basic syntax is:
document.cookie = "name=value; expires=date; path=path; domain=domain; secure";
Parameters:
- name=value: The name and value of the cookie
- expires: The expiration date (GMT format)
- path: The path for which the cookie is valid
- domain: The domain for which the cookie is valid
- secure: Specifies if cookie should only be sent over HTTPS
Example 27.1: Create a Simple Cookie
Create a cookie that stores the user's theme preference:
27.3 Reading Cookies
To read cookies, access the document.cookie
property which returns all cookies as a string:
// Get all cookies as a string const allCookies = document.cookie; // Parse cookies into an object function getCookies() { const cookies = {}; document.cookie.split(';').forEach(cookie => { const [name, value] = cookie.split('='); cookies[name.trim()] = decodeURIComponent(value); }); return cookies; }
Example 27.2: Read Multiple Cookies
Create and read multiple cookies:
27.4 Deleting Cookies
To delete a cookie, set its expiration date to a past date:
function deleteCookie(name) { document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`; }
Example 27.3: User Preferences
Store and retrieve user preferences using cookies:
27.5 Cookie Security
Security Best Practices:
- Always use the
Secure
flag for HTTPS-only cookies - Use the
HttpOnly
flag to prevent JavaScript access for sensitive cookies - Set appropriate expiration dates
- Consider SameSite attribute to prevent CSRF attacks
- Never store sensitive information in cookies
Example 27.4: Visit Counter
Create a cookie that counts page visits: