JavaScript tutorials > Web APIs and the DOM > Browser APIs > What are cookies and how do you manipulate them with JavaScript?
What are cookies and how do you manipulate them with JavaScript?
Cookies are small text files that websites store on a user's computer to remember information about them, such as login details, preferences, or shopping cart contents. This tutorial explores how to manipulate cookies using JavaScript, covering reading, writing, updating, and deleting cookies.
Understanding Cookies
Cookies are essentially key-value pairs stored in the user's browser. They are associated with a specific domain and path. When the browser makes a request to the server for that domain and path, the browser automatically includes the cookies in the request headers. Cookies can have expiration dates; if an expiration date is set, the cookie will be automatically deleted by the browser after that date. If no expiration date is set, the cookie is considered a session cookie and will be deleted when the browser is closed.
Setting a Cookie with JavaScript
The In the example above, we set a cookie named document.cookie
property is the primary way to manipulate cookies in JavaScript. Setting a cookie involves assigning a string to this property. This string should follow a specific format:name=value; expires=expiration_date; path=path
name
: The name of the cookie.value
: The value of the cookie.expires
: (Optional) The expiration date of the cookie in UTC format. If not specified, the cookie will be a session cookie.path
: (Optional) The path for which the cookie is valid. Defaults to the current directory of the page. Setting path=/
makes the cookie available for the entire domain.username
with the value John Doe
. The cookie will expire on December 18, 2024, and is valid for the entire domain.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";
Reading Cookies with JavaScript
Reading cookies is also done through the The example above reads all cookies and logs them to the console. Note that this will print a string containing all cookies concatenated together.document.cookie
property. However, when reading, it returns a string containing all cookies for the current document, separated by semicolons. To get the value of a specific cookie, you need to parse this string.
let cookies = document.cookie;
console.log(cookies); // Output: username=John Doe; otherCookie=someValue
Parsing Cookies to Extract a Specific Value
This function getCookie(name)
parses the document.cookie
string to retrieve the value of a cookie with the specified name.
null
.
function getCookie(name) {
const cookieString = document.cookie;
const cookiesArray = cookieString.split(';');
for (let i = 0; i < cookiesArray.length; i++) {
let cookie = cookiesArray[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1);
}
}
return null;
}
let username = getCookie("username");
console.log(username); // Output: John Doe
Updating a Cookie
Updating a cookie is the same as setting a cookie. You simply set a new cookie with the same name, but a different value and/or expiration date. In the example above, we update the username
cookie to Jane Doe
. Make sure you include the path
attribute, since omitting it might result in the cookie not being updated correctly, especially if the original cookie was set with a specific path.
document.cookie = "username=Jane Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";
Deleting a Cookie
To delete a cookie, you set its expiration date to a past date. The browser will then automatically remove the cookie. In the example above, we set the expiration date of the username
cookie to January 1, 1970, effectively deleting it. Again, ensuring the path
attribute matches the original cookie's path is crucial for successful deletion.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Concepts Behind the Snippet
The key concepts behind cookie manipulation in JavaScript involve understanding the document.cookie
property, the format of cookie strings, and the importance of the expires
and path
attributes. Cookies are client-side data storage mechanisms that allow websites to persist information across multiple requests. Because they are sent with every HTTP request, it's crucial to be mindful of their size and the amount of data stored within them to avoid performance issues.
Real-Life Use Case Section
Cookies are frequently used for: For example, an e-commerce site might use cookies to remember a user's shopping cart items. When the user returns to the site, the cookies are read, and the shopping cart is automatically populated with the previously selected items.
Best Practices
Secure
attribute to ensure the cookie is only transmitted over HTTPS.path
and domain
attributes to limit the scope of the cookie.HttpOnly
attribute to prevent client-side scripts from accessing the cookie, reducing the risk of cross-site scripting (XSS) attacks (This needs to be set server-side).SameSite
attribute to control how cookies are sent with cross-site requests, providing protection against cross-site request forgery (CSRF) attacks (This needs to be set server-side).
Interview Tip
When discussing cookies in an interview, be sure to emphasize your understanding of: Be prepared to discuss the limitations of cookies and the situations where alternative storage mechanisms might be more appropriate.
Secure
, HttpOnly
, and SameSite
attributes.localStorage
and sessionStorage
, and their differences from cookies.
When to Use Them
Use cookies when you need to store small amounts of data that need to be transmitted with every HTTP request. They are suitable for: Avoid using cookies for large amounts of data or sensitive information that doesn't need to be transmitted with every request. In those cases, consider using
localStorage
, sessionStorage
, or server-side storage mechanisms.
Memory Footprint
Cookies have a relatively small memory footprint. However, because they are sent with every HTTP request, excessive use of large cookies can negatively impact website performance. Browsers typically limit the size of individual cookies (around 4KB) and the total number of cookies a website can store (around 50 per domain). It's important to monitor the size and number of cookies used on your website to ensure they don't become a performance bottleneck.
Alternatives
Alternatives to cookies include:
Pros
document.cookie
property provides a simple API for reading and writing cookies.
Cons
FAQ
-
What is the maximum size of a cookie?
The maximum size of a cookie is approximately 4KB. -
How do I make a cookie secure?
To make a cookie secure, use theSecure
attribute to ensure it's only transmitted over HTTPS. Server-side, set theHttpOnly
attribute to prevent client-side scripts from accessing it, and use theSameSite
attribute to protect against CSRF attacks. -
Are cookies the only way to store data client-side?
No, there are other options, such aslocalStorage
,sessionStorage
, and IndexedDB. Each option has its own advantages and disadvantages, depending on the specific use case.