How to Set Cookie in JavaScript: Simple Guide
To set a cookie in JavaScript, assign a string to
document.cookie with the format name=value and optional attributes like expires or path. For example, document.cookie = "username=John; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/"; sets a cookie named "username".Syntax
Setting a cookie uses the document.cookie property with a string in this format:
- name=value: The cookie's name and its value.
- expires=DATE (optional): When the cookie expires, in GMT string format.
- path=PATH (optional): The URL path where the cookie is valid.
- domain=DOMAIN (optional): The domain for the cookie.
- secure (optional): Makes the cookie sent only over HTTPS.
Each part is separated by a semicolon and a space.
javascript
document.cookie = "name=value; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";Example
This example sets a cookie named user with value Jane that expires in 7 days and is valid for the whole website.
javascript
const daysToExpire = 7; const date = new Date(); date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000)); const expires = "expires=" + date.toUTCString(); document.cookie = "user=Jane; " + expires + "; path=/"; console.log(document.cookie);
Output
user=Jane
Common Pitfalls
Common mistakes when setting cookies include:
- Not setting
expiresormax-age, which creates a session cookie that disappears when the browser closes. - Forgetting the
path, which may limit cookie availability to certain pages. - Using spaces or special characters in names or values without encoding.
- Trying to set cookies on domains or protocols that are not allowed.
Always encode cookie values with encodeURIComponent if they contain special characters.
javascript
/* Wrong way: value with spaces without encoding */ document.cookie = "name=John Doe; path=/"; /* Right way: encode the value */ document.cookie = "name=" + encodeURIComponent("John Doe") + "; path=/";
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| name=value | Sets the cookie name and value | user=Jane |
| expires | Expiration date in GMT string | expires=Fri, 31 Dec 9999 23:59:59 GMT |
| max-age | Expiration in seconds | max-age=3600 |
| path | URL path where cookie is valid | path=/ |
| domain | Domain for the cookie | domain=example.com |
| secure | Send cookie only over HTTPS | secure |
| SameSite | Controls cross-site sending | SameSite=Strict |
Key Takeaways
Set cookies by assigning a formatted string to document.cookie.
Always specify expires or max-age to control cookie lifetime.
Use encodeURIComponent to safely encode cookie values with special characters.
Include path to control where the cookie is accessible.
Secure cookies with the secure attribute when using HTTPS.