When you visit your favorite online learning platform, like Intellipaat, to watch coding tutorials. Once you log in to the website, the website remembers you the next time as well without asking to log in again. But how does the website remember you even after you close the browser or restart the computer? This happens using cookies. A cookie is used by a website to help it remember you (your session). In this article, we will understand what JavaScript cookies are and how they work in browsers. We will also learn how to create, read, update, and delete them in JavaScript. Let’s start.
What Are JavaScript Cookies?
A cookie is a small piece of data that a website stores on a user’s browser. When you visit a website, it can send a cookie to your browser, which stores it locally. These cookies help the website remember information about you, such as your preferences, login status, or session information.
On the other hand, JavaScript cookies are cookies that can be accessed and manipulated directly from the browser using JavaScript. A few examples include storing a user’s preferred language, keeping track of the number of times a user has visited a page, or saving form input data temporarily so it doesn’t get lost on page reload. This way, a user can have a more personalized and seamless user experience and would be more likely to visit the website again.
JavaScript cookies consist of key-value pairs and can hold additional attributes in the same cookie, such as expires, path, domain, and secure.
In the example above, the JavaScript stored key-value pairs for attributes like user_id, session-token, and theme.
Important Note:
Multiple key-value pairs are stored as separate cookies, and all these are sent in a single request. When the browser sends a request to the server, all cookies for the domain are sent together in a single HTTP request header (as a semicolon-separated string).
The above note is a brief glimpse of how JavaScript cookies work. Let us now look at its working in detail.
How Do Cookies Work in JavaScript?
A JavaScript cookie will save a small piece of data that helps the server identify the browser and user. This cookie is saved in the user’s browser itself. After that, whenever a domain makes an HTTP request, the browser automatically sends this cookie back with the request to the server of that domain.
This enables the server to recognize returning users and provide a more personalized experience.
The process of working with cookies in JavaScript involves four main operations:
- Creating a Cookie
- Reading Cookie
- Updating a Cookie
- Deleting a Cookie
In addition to these operations, JavaScript cookies can also have attributes that control how long they last, where they are accessible, and how securely they are transmitted. In later sections, we will learn how these attributes help developers manage JavaScript cookies efficiently.
But before that, let’s first discuss the four major operations performed on JavaScript cookies in detail.
Creating JavaScript Cookies
In JavaScript, cookies are created using the document.cookie method, which is built into the programming language itself. You can store data by assigning a key-value pair to a document.cookie. This tells the browser to save the cookie locally for the current domain (the website you have opened). For example,
document.cookie = "username=GarimaHansa";
This created a JavaScript cookie with the key “username” and the value “GarimaHansa”.
By default, cookies are stored as session cookies. This means that when the browser is closed, these JavaScript cookies are deleted. If you want to extend its life past the closing of the browser, you can set it using the expires attribute. It can be done using
document.cookie = "username=GarimaHansa; expires=Fri, 31 Dec 2025 12:00:00 UTC";
Now, the cookie will stay stored in the browser until 31 December 2025.
Reading Cookies in JavaScript
Once your cookies are created, you can read them using the same document.cookie property. Remember, this property will return all the cookies saved for the current domain as a single string. All the key-value pairs will be separated using semicolons (;). For example, let us try to read the cookie we created in the previous example. To read (print), we will use the console.log() function.
Code:
Output:
Explanation: When we use console.log(document.cookie), it displays all cookies available for the current domain as a semicolon-separated string. In the example above, you can see existing cookies set by other services (like Google Analytics), along with the custom cookies we created: username=GarimaHansa and theme=dark. These cookies are sent to the server with every HTTP request made to the domain.
Updating and Deleting Cookies
To update JavaScript cookies, you simply set a new value for the same cookie key using the document.cookie again property. The browser will then overwrite the existing cookie with the new value. For example, let us try and update the theme from dark to light for the cookie we created earlier.
Example:
Output:
Explanation: As you can see, only the theme value has changed. Rest all the other values remain the same.
To delete JavaScript cookies, all you have to do is simply but the value of the expires attribute to a date that has already passed. This will cause the browser to remove the cookie.
Code:
Output:
Explanation: As you can see, the theme cookie has been deleted from the browser storage. All we did was change the expires attribute to 01 Jan 1970, a date that has passed.
By updating and deleting cookies, developers can manage user sessions and preferences efficiently, giving users a seamless and personalized experience.
Let us now dive deeper into the concept of attributes in JavaScript cookies, and also look at some important cookies you must know about.
Cookie Attributes Explained
When creating cookies in JavaScript, you can define additional attributes that control how cookies behave, such as their lifespan, scope, and security. To set multiple attributes in a single cookie, you chain them in the same string, separated by semicolons. Each assignment is to be documented.cookie sets or updates a single cookie, and all desired attributes must be included in the same string.
Attribute | Description | Example |
expires | Specifies the expiration date of the cookie. After this date, the cookie will be deleted automatically. | document.cookie = “username=GarimaHansa; expires=Fri, 31 Dec 2025 12:00:00 UTC; path=/;” |
path | Defines the URL path where the cookie is accessible. Default is the path of the page that created it. | document.cookie = “theme=dark; path=/;” |
domain | Specifies the domain for which the cookie is valid, allowing subdomains to access it. | document.cookie = “user_id=USR123; domain=example.com; path=/;” |
secure | Ensures the cookie is sent only over HTTPS connections. | document.cookie = “session_token=abc123; secure; path=/;” |
SameSite | Controls cross-site request behavior to prevent CSRF attacks. | document.cookie = “preferences=dark-mode; SameSite=Lax; path=/;” |
HttpOnly | Prevents client-side JavaScript from accessing the cookie, improving security. | Set-Cookie: session=abc123; HttpOnly; path=/; |
Max-Age | Specifies the cookie’s lifetime in seconds, overriding expires. | document.cookie = “user=JohnDoe; Max-Age=3600; path=/;” |
Priority | Indicates the importance of the cookie (Low, Medium, High). Helps the browser manage cookie eviction. | document.cookie = “id=123; Priority=High; path=/;” |
SameParty | Restricts cookies to same-party contexts in browsers that support it, improving privacy. | document.cookie = “tracking=abc; SameParty; path=/;” |
Partitioned | Limits the cookie to a single first-party context, helping avoid cross-site tracking. | document.cookie = “prefs=dark-mode; Partitioned; path=/;” |
Knowing and setting these attributes benefits developers in the control of JavaScript cookies and creates safer and more predictable behavior for web applications. You might be thinking that storing data related to the previous session may be a security threat. Time to see how JavaScript has dealt with this issue.
Security Concerns with Cookies
While JavaScript cookies are useful for improving the user experience when remembering session preferences and information, they are associated with potential security threats and risks. This means that developers have to be aware of them and manage them appropriately. Below are a few key concepts used that you should be aware of when working with JavaScript cookies:
1. Cross-Site Scripting (XSS) Attacks
A website that is vulnerable to XSS attacks, malicious scripts can run in the user’s browser and access cookies via document.cookie. This puts sensitive information like session tokens and user IDs in a vulnerable spot.
To handle this,
- You can use the HttpOnly attribute when setting cookies that contain sensitive data.
- Or you can also filter the user input to prevent malicious scripts from running.
2. Cross-Site Request Forgery (CSRF) Attacks
Cross-Site Request Forgery (CSRF) attacks exploit the browsers’ automatic inclusion of JavaScript cookies with every HTTP request to a given domain. Attackers can then send malicious requests using the attached information of the already established session.
To handle this risk,
- You should set the SameSite attribute to one of these values (Strict or Lax), which will help you control when these JavaScript cookies are sent in cross-site requests.
- Or, you can implement CSRF tokens to verify that requests are coming from trusted sources.
3. Cookie Theft Over Insecure Connections
When cookies are transmitted over HTTP connections that are unencrypted, they get intercepted by attackers using man-in-the-middle (MITM) attacks.
To avoid this,
- You should always use the Secure attribute to ensure cookies are only sent over HTTPS (secured) connections.
4. Excessive Cookie Size
Web browsers have imposed maximum cookie storage limits on total file size per domain. In addition to the limits on total storage, individual cookies can only be 4KB or less in size. Hence, if designers save too much data inside JavaScript cookies the browsers will truncate the data or ignore the cookie altogether.
To handle your cookies from getting truncated,
- Store only the important information in cookies (e.g., session ID) and use server-side storage for larger data.
5. Cookie Expiry Mismanagement
It is important that you create JavaScript cookies with assigned expiration dates. If you forget to do that, your cookie will be stored in the memory indefinitely, which will lead to stale or outdated data being used unintentionally. This will not only butcher the user experience of the website but also might lead to errors in information.
It is important to mitigate this, which is done by
- setting appropriate expires or Max-Age values when creating cookies to control their lifespan.
Through knowledge about these security practices and their application, the developers can make sure that there is a tremendous cut to the risk of exposing sensitive user information, unauthorized access, and a more secure and reliable web application.
Practical Use Cases of Cookies
We have discussed how cookies are used to save your login information so that you would not have to log in every time you refresh your browser. There are more practical ways to use JavaScript cookies. We have listed some of them below so that you can interpret the importance of JavaScript cookies. It really enhances your user experience and efficient functioning.
- Tracking User Behavior: Websites regularly use cookies to track user activity, like pages visited, time spent, and click patterns, so that they can personalize your ads. This is how, when you search for a product, you start getting the ads related to that on other websites as well.
- Shopping Cart Management: The carts that you fill in an E-commerce website use cookies to store the contents and navigate with the same cart. This makes it so easy for you since you do not have to fill it in again and again.
- Form Data Persistence: When users fill out long forms, developers use cookies to temporarily store entered data, so if the page reloads or the user accidentally closes the browser, the application retains the information and prevents data loss.
- A/B Testing: Cookies help remember which version of a given web page a user is shown during A/B testing experiments. This helps establish consistency on later visits so developers can replicate performance measures x times in order to have reliable chain-of-causation analysis.
- Storing User Preferences:In the previous example, we saw how the webpage theme was saved in cookies. Similarly, developers use cookies to save user preferences such as font size or layout language, which helps improve the user experience through personalization.
Limitations of JavaScript Cookies
But are JavaScript cookies sufficient? Definitely not. There are some limitations to what JavaScript cookies can accomplish. Below, we have listed the major disadvantages of JavaScript cookies.
- Limited Storage Capacity: Each cookie is allowed 4 KB of data, which limits the amount of data that can be stored. Since data such as images, videos, or large application state requires more space, developers use technologies like localStorage or IndexedDB to store it efficiently.
- Sent with Every HTTP Request: These cookies are sent to the server with each HTTP request. This increases network traffic and can negatively impact the overall performance.
- Security Risks: JavaScript Cookies can be exploited to security threats such as Cross-site Scripting (XSS) and Cross-site Request Forgery (CSRF) attacks under improper management. This is the reason why developers do not save important information in such cookies. You might, but you must exercise caution with such security attributes as Secure and HttpOnly must be used.
- Limited to Same-Origin Policy: These cookies are limited and accessible only to the domain that created them. This restriction prevents the sharing of data across different domains, which cross-site applications often require, so developers must use other solutions, such as server-side storage or OAuth.
- Manual Management Required: Unlike localStorage or sessionStorage, developers must handle cookies manually, paying particular attention to their attributes, expiration, path, and security options. If they fail to do this correctly, cookies may last longer than desired or fail to be sent when required.
As a developer, keeping all these limitations in mind will help you find a better and efficient storage system when designing your own website.
Common Mistakes Beginners Make with Cookies
Keeping all the advantages and disadvantages of JavaScript cookies in mind, let us discuss some of the common mistakes that you, as a beginner, can make when using JavaScript Cookies. Avoiding these from the get-go will save you a lot of time. With each mistake, we also listed down the best practices that you can follow to avoid such occurrences:
1. Storing Sensitive Data in Cookies
You have become quite familiar with the property of JavaScript cookies that it is sent with every HTTP request made. This makes it vulnerable to cyber attacks, and storing sensitive information in cookies might add security risks.
Best Practice: Store only non-sensitive data in cookies and use HttpOnly and Secure attributes for extra protection.
2. Not Setting Proper Expiration
Sometimes, beginners forget to set the expires or max-age attributes, which causes the cookie to be treated as a session cookie. This means that the cookie is deleted when the browser is closed, which may not be the intended behavior.
Best Practice: You should always set an appropriate expiration time based on the purpose of the cookie.
3. Overwriting Existing Cookies Accidentally
When setting cookies using document.cookie, beginners may unintentionally overwrite existing cookies by not using unique names or neglecting to handle multiple attributes correctly.
Best Practice: Always remember to specify full attributes (like path, expires) and use unique cookie names to avoid any confusion and collisions.
4. Assuming Cookies Work Across Subdomains Automatically
This is not the case; a cookie is only accessible to the domain that created it. A cookie set on example.com is not accessible on sub.example.com.
Best Practice: You can use the domain attribute explicitly if you want the cookie to be shared across subdomains.
5. Not Using Secure and SameSite Attributes
Security should always be your priority whenever developing your own website. Beginners often neglect security-related attributes, leaving cookies vulnerable to attacks such as CSRF or XSS.
Best Practice: Always use Secure for HTTPS-only transmission and SameSite=Lax or Strict to prevent cross-site request forgery.
Conclusion
JavaScript Cookies are fundamental to enhancing the user experience of a website by allowing it to store small pieces of data directly in a user’s browser. From storing session data to user preferences, cookies offer a simple and effective way to build personalized web applications. However, you must understand its limitations and potential security risks. This article also discussed the common mistakes that a beginner tends to make. You should manage your JavaScript cookies responsibly to build safe and efficient web applications.
With the right knowledge and practices, cookies will remain a powerful ally in your web development toolkit.
Useful Resources
JavaScript Cookies – FAQs
Q1. What are the cookies in JavaScript?
Cookies in JavaScript are small text files stored by the browser that hold data like user preferences, session info, and tracking identifiers, enabling websites to remember user activity.
Q2. How do I enable cookies in JavaScript?
Cookies are enabled by default in browsers. JavaScript can read, write, and manage cookies using the document.cookie object.
Q3. Can you set cookies with JavaScript?
Yes, use document.cookie = “key=value; expires=date; path=/” to set cookies in JavaScript with optional expiration and path attributes.
Q4. Can JavaScript access all cookies?
JavaScript can only access cookies from the same domain and path. Cookies marked HttpOnly are inaccessible to JavaScript for security reasons.
Q5. Can JavaScript delete cookies?
Yes, delete a cookie by setting its expiration date to the past: document.cookie = "key=value; expires=Thu, 01 Jan 1970 00:00:00 UTC;"
Q6. What are the main types of cookies?
Main types include session cookies (temporary) and persistent cookies (stored long-term), used for sessions, preferences, and tracking.