How to Set Cookies in JavaScript: A Comprehensive Guide

Cookies are small pieces of data stored on a user’s browser by websites. They are commonly used to remember user preferences, track user sessions, and store data temporarily. In this guide, we will explore how to set cookies using JavaScript, including various scenarios and best practices.

What is a Cookie?

A cookie is a text file stored on a user’s browser. It contains key-value pairs that can be read by the website that set them. Cookies are sent back to the server with each request, allowing the server to remember information about the user.

How to Set a Cookie in JavaScript

JavaScript provides a method to set cookies using the document.cookie property. The basic syntax for setting a cookie is:

// Set a cookie
document.cookie = "key=value";

Example: Setting a Simple Cookie

// Set a cookie with the name 'username' and value 'JohnDoe'
document.cookie = "username=JohnDoe";

Example: Setting a Cookie with Expiration

By default, cookies expire when the browser is closed. To set a persistent cookie, you need to specify an expiration date:

// Set a cookie with expiration in 7 days
const expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 7);

const cookie = "username=JohnDoe; expires=" + expireDate.toUTCString();
document.cookie = cookie;

Example: Setting a Secure Cookie

Secure cookies are only sent over HTTPS. To set a secure cookie, include the Secure flag:

// Set a secure cookie
const cookie = "username=JohnDoe; Secure";
document.cookie = cookie;

Example: Setting a SameSite Cookie

The SameSite attribute prevents cookies from being sent with cross-site requests, reducing the risk of CSRF attacks. Possible values are Strict, Lax, or None:

// Set a SameSite cookie
const cookie = "username=JohnDoe; SameSite=Strict";
document.cookie = cookie;

Example: Setting a Path for a Cookie

By default, cookies are available to all paths on the domain. To restrict a cookie to a specific path, use the Path attribute:

// Set a cookie available only to '/admin' path
const cookie = "username=JohnDoe; Path=/admin";
document.cookie = cookie;

Frequently Asked Questions (FAQ)

1. What is the maximum size of a cookie?

The maximum size of a cookie is typically around 4KB, though this can vary by browser. Exceeding this limit may cause the cookie to be truncated or ignored.

2. Can cookies be set across subdomains?

Yes, by including the domain in the cookie. For example, Domain=example.com allows the cookie to be shared across all subdomains of example.com.

3. What happens if a cookie’s expiration date has passed?

The browser automatically deletes the cookie when its expiration date is reached.

4. Can cookies be used for session management?

Yes, cookies are commonly used for session management. Session cookies are deleted when the browser is closed and do not have an expiration date.

5. How do I read a cookie in JavaScript?

You can read all cookies using document.cookie, which returns a string of key-value pairs separated by semicolons. To read a specific cookie, you need to parse the string:

// Read all cookies
console.log(document.cookie);

// Function to get a specific cookie
function getCookie(name) {
  const cookies = document.cookie.split(';');
  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i].trim();
    if (cookie.startsWith(name + '=')) {
      return cookie.substring(name.length + 1);
    }
  }
  return null;
}

// Get the value of 'username'
const username = getCookie('username');
console.log(username);

Conclusion

Setting cookies in JavaScript is a fundamental skill for web developers. By understanding how to set and manage cookies, you can enhance user experience, track user sessions, and implement security measures like the Secure and SameSite flags. Always remember to follow best practices, such as limiting cookie size and using secure settings, to ensure a safe and efficient implementation.

Index
Scroll to Top