Writing Cookies
Writing Cookies
Section titled “Writing Cookies”Introduction
Section titled “Introduction”Set cookies by assigning to document.cookie. Each assignment creates or updates a single cookie.
Basic Writing
Section titled “Basic Writing”// Set a cookie (key=value)document.cookie = 'theme=dark';Cookie Options
Section titled “Cookie Options”document.cookie = 'session=abc123; path=/; max-age=86400; Secure; SameSite=Strict';
// Options:// path=/ — Available on all paths// max-age=86400 — Expires in 24 hours (seconds)// Secure — Only over HTTPS// SameSite=Strict — Block cross-site requests// domain=.example.com — Share with subdomainsUsing Expires
Section titled “Using Expires”// Set expiration dateconst expires = new Date();expires.setDate(expires.getDate() + 7); // 7 days from nowdocument.cookie = `premium=true; expires=${expires.toUTCString()}; path=/`;Summary
Section titled “Summary”document.cookie = 'key=value'sets a cookie- Append options after the value:
; path=/; max-age=86400 Secureflag restricts to HTTPS onlySameSite=Strictprevents CSRF attacksmax-agesets expiration in seconds