document.cookie
String-based interface for non-HttpOnly cookies.
Cookies are small pieces of data attached to a site. They can be sent with HTTP requests and controlled with attributes.
document.cookie = "theme=dark; Path=/; SameSite=Lax"; console.log(document.cookie);
Browser APIs & BOM
Cookies are often used for sessions, preferences and server-side state. Unlike localStorage, cookies can be sent to the server with requests.
JavaScript can read and write non-HttpOnly cookies through document.cookie. HttpOnly cookies are intentionally hidden from JavaScript.
Cookie attributes such as Path, Max-Age, Secure, HttpOnly and SameSite decide where cookies apply and how safely they behave.
String-based interface for non-HttpOnly cookies.
Server-set attribute that hides a cookie from JavaScript.
Sends cookie only over HTTPS.
Controls cross-site cookie behavior.
Examples
document.cookie = "theme=dark; Path=/; Max-Age=2592000; SameSite=Lax; Secure";
document.cookie = `token=${token}; Path=/`;
Code patterns
These examples focus on practical browser APIs: URL state, storage, cookies, clipboard, permissions, observers and offline-capable platform tools.
Include basic attributes.
document.cookie = "theme=dark; Path=/; Max-Age=2592000; SameSite=Lax";
document.cookie returns a semicolon-separated string.
const allCookies = document.cookie;
Expire it with Max-Age=0.
document.cookie = "theme=; Path=/; Max-Age=0; SameSite=Lax";
Sensitive session cookies should usually be HttpOnly from the server.
// Set-Cookie: session=...; HttpOnly; Secure; SameSite=Lax
Rules that matter
Browser APIs are powerful because they touch privacy, navigation, storage, permissions and performance. Use them deliberately.
JavaScript should not read session tokens.
Sensitive cookies should not travel over plain HTTP.
It helps reduce cross-site request risk.
Cookies can be sent with requests.
Scope determines where cookies apply.
Analytics and marketing cookies can require consent depending on jurisdiction.
Production thinking
Cookies sit at the boundary between browser and server, so mistakes can become security and privacy problems.
Cookie banners and preference controls should be keyboard accessible and clearly worded.
Production authentication cookies should be set by the server with HttpOnly, Secure and SameSite where appropriate.
Cookie walls and consent overlays should not block crawlable content unnecessarily.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain support, permissions, fallback and cleanup, you are ready to use the API responsibly.
Senior audit upgrade