0
0
JavascriptHow-ToBeginner · 3 min read

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 expires or max-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

AttributeDescriptionExample
name=valueSets the cookie name and valueuser=Jane
expiresExpiration date in GMT stringexpires=Fri, 31 Dec 9999 23:59:59 GMT
max-ageExpiration in secondsmax-age=3600
pathURL path where cookie is validpath=/
domainDomain for the cookiedomain=example.com
secureSend cookie only over HTTPSsecure
SameSiteControls cross-site sendingSameSite=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.