- 1 1. Introduction
- 2 2. What Is a Cookie?
- 3 3. Basic Cookie Operations in JavaScript
- 4 4. Cookie Attribute Settings
- 5 5. Practical Code Examples
- 6 6. Using Third-Party Libraries
- 7 7. Security and Privacy Considerations
- 8 8. How to Check Cookies in Your Browser
- 9 9. Summary
1. Introduction
In web development using JavaScript, cookies are widely used as an important mechanism for storing user-related information.
For example, they are commonly used to maintain login sessions or store shopping cart data, significantly improving user convenience.
However, for beginners, concepts such as “What is a cookie?” or “How can cookies be manipulated with JavaScript?” can be difficult to understand.
In this article, we provide a detailed explanation of JavaScript cookie handling, from basic concepts to advanced usage.
With practical code examples, this guide is designed to be useful for both beginners and intermediate developers.
2. What Is a Cookie?
Basic Concept of Cookies
A cookie is a small piece of data stored in a web browser.
It is mainly used for the following purposes:
- Storing information entered by users on a website (e.g., login credentials).
- Recording visitor behavior for marketing and analytics purposes.
- Preserving configuration settings (e.g., language preferences or theme settings) to improve user experience.
How Cookies Work
Cookies are composed of key-value pairs and are stored in the following format:
name=value; expires=Wed, 31 Dec 2025 23:59:59 GMT; path=/In this example, the key name is assigned the value value, along with an expiration date and a specified path.
Main Components of a Cookie
- Name and Value (name=value) – The basic information of the cookie.
- Expiration (expires or max-age) – Specifies how long the cookie remains valid.
- Path – Defines the directory or pages where the cookie is accessible.
- Secure Attribute – Ensures the cookie is sent only over HTTPS connections.
- SameSite Attribute – Helps protect against cross-site request attacks.
These flexible settings make cookies useful for enhancing user experience while strengthening security.
3. Basic Cookie Operations in JavaScript
In JavaScript, cookies are manipulated using the document.cookie property.
This section introduces the basic operations.
Setting a Cookie
Below is an example of how to create a new cookie.
document.cookie = "username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";Key Points:
username=John: Specifies the key and value.expires: Sets the expiration date. If omitted, the cookie is deleted when the browser is closed.path=/: Makes the cookie available across the entire site.
Getting Cookies
All cookies can be retrieved as follows:
console.log(document.cookie);Example output:
username=John; theme=dark; lang=jaSince multiple cookies are separated by semicolons (;), you need to split the string when processing individual values.
Deleting a Cookie
To delete a cookie, set its expiration date to a past date.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";This code removes the cookie named username.
4. Cookie Attribute Settings
Cookie attributes play an important role in security and expiration control.
Setting Expiration
- Using the expires attribute (date-based)
document.cookie = "username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";- Using the max-age attribute (seconds-based)
document.cookie = "username=John; max-age=3600; path=/";This configuration automatically deletes the cookie after one hour.
Security Attributes
- secure attribute (HTTPS only)
document.cookie = "username=John; secure";- SameSite attribute (cross-site request protection)
document.cookie = "username=John; SameSite=Strict";By properly configuring these attributes, you can significantly improve security and privacy protection.
5. Practical Code Examples
Counting User Visits
function getCookie(name) {
let cookies = document.cookie.split('; ');
for (let i = 0; i < cookies.length; i++) {
let parts = cookies[i].split('=');
if (parts[0] === name) return parts[1];
}
return null;
}
function setCookie(name, value, days) {
let expires = "";
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
let visits = getCookie("visits") ? parseInt(getCookie("visits")) : 0;
visits++;
setCookie("visits", visits, 365);
alert("Your number of visits: " + visits);This code stores the number of user visits in a cookie and updates the count on each visit.

6. Using Third-Party Libraries
Although cookies can be managed using the document.cookie property in JavaScript, handling strings and setting attributes can become cumbersome.
This often results in longer code and reduced readability.
To simplify cookie management, using third-party libraries is a common and effective approach.
In this section, we focus on one of the most popular libraries: js-cookie.
1. What Is the js-cookie Library?
js-cookie is a lightweight JavaScript library that simplifies cookie operations.
Its main features include:
- Simple API: Easily set, get, and delete cookies.
- Extensibility and flexibility: Supports security options and custom configurations.
- Lightweight: Only about 2 KB after minification.
2. Installing js-cookie
Loading via CDN
Add the following code inside the <head> tag of your HTML file.
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js"></script>Installing via npm or yarn
If you manage dependencies in your project, use one of the following commands:
npm install js-cookieor
yarn add js-cookie3. Basic Usage
Setting a Cookie
Cookies.set('username', 'John', { expires: 7 }); // Valid for 7 daysGetting a Cookie
let username = Cookies.get('username');
console.log(username); // Output: JohnDeleting a Cookie
Cookies.remove('username');4. Advanced Option Settings
Setting expiration and path
Cookies.set('session', 'active', { expires: 1, path: '/' });- expires: Expires after 1 day.
- path: Makes the cookie available site-wide.
Adding the secure attribute
Cookies.set('secureData', 'secret', { secure: true });- secure: true: Sends the cookie only over HTTPS.
Specifying the SameSite attribute
Cookies.set('strictCookie', 'value', { sameSite: 'Strict' });- sameSite: ‘Strict’: Blocks cross-site requests and enhances security.
7. Security and Privacy Considerations
When working with cookies in JavaScript, security measures and privacy protection are extremely important.
Improper handling may lead to data leaks or unauthorized access.
This section explains best practices for secure cookie management.
1. Security Measures
Using HTTPS and the Secure Attribute
Set the Secure attribute so cookies are sent only over HTTPS connections.
This helps prevent data interception and tampering.
Example:
document.cookie = "sessionID=abc123; Secure";When using the third-party library js-cookie, you can configure it as follows:
Cookies.set('sessionID', 'abc123', { secure: true });Using the HttpOnly Attribute (Server-Side Configuration)
JavaScript cannot set the HttpOnly attribute on the client side.
However, configuring this attribute on the server side helps prevent
XSS (Cross-Site Scripting) attacks.
Example: Server-side configuration (PHP)
setcookie('sessionID', 'abc123', [
'httponly' => true,
'secure' => true,
'samesite' => 'Strict'
]);Preventing CSRF Attacks with the SameSite Attribute
To prevent CSRF (Cross-Site Request Forgery) attacks,
configure the SameSite attribute.
Example:
document.cookie = "token=secureToken; SameSite=Strict";2. Privacy Protection
Limit the Type of Stored Information
Avoid storing personal or sensitive information (such as passwords) in cookies.
Instead, store anonymous identifiers such as session IDs and validate them on the server side.
Example: Using a session ID
Cookies.set('sessionID', 'randomString123', { secure: true, httpOnly: true });Compliance with GDPR and Privacy Regulations
Due to regulations such as the GDPR (General Data Protection Regulation) in the EU
and Japan’s Act on the Protection of Personal Information,
the following requirements apply when using cookies:
- Mandatory user consent Users must be informed about the purpose of cookie usage and provide explicit consent.
- Providing opt-in and opt-out options Users must be able to refuse non-essential cookies.
Example: Cookie consent banner (JavaScript)
if (!Cookies.get('cookieConsent')) {
let consent = confirm('This site uses cookies. Do you allow cookies?');
if (consent) {
Cookies.set('cookieConsent', 'true', { expires: 365 });
}
}8. How to Check Cookies in Your Browser
When setting, retrieving, or deleting cookies with JavaScript,
you can verify their behavior using browser developer tools.
This section explains how to check cookies in major browsers.
1. Checking Cookies in Google Chrome
Opening Developer Tools
- Right-click on the page and select “Inspect” or “Inspect Element”.
- Or press F12 or Ctrl + Shift + I (on Mac: Cmd + Opt + I).
Steps to View Cookies
- Select the “Application” tab in the developer tools.
- From the left menu, click “Storage” → “Cookies”.
- Select the target domain from the list.
Viewing Cookie Details
Cookies for the selected site are displayed in a table format.
Each column represents the following information:
| Column | Description |
|---|---|
| Name | Cookie name (key) |
| Value | Stored value |
| Domain | Applicable domain |
| Path | Applicable path |
| Expires / Max-Age | Expiration date |
| Size | Cookie size (bytes) |
| HttpOnly | Whether HttpOnly is enabled (not accessible via JavaScript) |
| Secure | Whether Secure is enabled (HTTPS only) |
| SameSite | SameSite setting (Strict, Lax, None) |
Editing and Deleting Cookies
- Edit: Double-click a row to modify its value.
- Delete: Select a row and press the Delete key, or right-click and choose Delete.
2. Checking Cookies in Firefox
Opening Developer Tools
- Right-click on the page and select “Inspect”.
- Or press F12 or Ctrl + Shift + I.
Viewing Cookies
- Select the “Storage” tab.
- Click “Cookies” from the left menu.
- Select the target site from the displayed domains.
Editing and Deleting
As in Chrome, you can directly edit values or delete cookies.
3. Checking Cookies in Safari (for Mac Users)
Enabling Developer Tools
- Open “Settings” from the Safari menu.
- Select the “Advanced” tab and check “Show Develop menu in menu bar”.
Opening Developer Tools
- Right-click on the page and select “Inspect Element”.
- Or press Cmd + Opt + I.
Viewing Cookies
- Select the “Storage” tab.
- Choose “Cookies” to review their contents.
4. Checking Cookies via the Console
Cookies can also be inspected using the JavaScript console.
Example: Display all cookies
console.log(document.cookie);Example: Retrieve a specific cookie
let cookies = document.cookie.split('; ');
let username = cookies.find(row => row.startsWith('username=')).split('=')[1];
console.log(username);Cookies can also be added or removed directly from the console.

9. Summary
In the previous sections, we have covered cookie handling in JavaScript
from basic concepts to advanced use cases.
This section reviews the key points and summarizes practical best practices.
1. Cookie Basics and How They Work
Cookies are a mechanism for storing small pieces of data in a web browser.
- Use cases: Maintaining login sessions, managing user preferences, and tracking behavior.
- Components: Key-value pairs, expiration settings, paths, domains, and security attributes.
Understanding these fundamentals allows you to adapt cookies flexibly to various scenarios.
2. Cookie Operations in JavaScript
In JavaScript, you can easily set, retrieve, and delete cookies using the
document.cookie property.
Example: Setting a cookie
document.cookie = "username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";Example: Getting cookies
console.log(document.cookie);Example: Deleting a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";These examples cover the basics, but for more complex requirements,
using a third-party library is recommended.
3. Using Third-Party Libraries
Libraries make cookie management significantly easier and more readable.
Example using js-cookie
Cookies.set('username', 'John', { expires: 7, secure: true });
let username = Cookies.get('username');
Cookies.remove('username');Advantages:
- Short and intuitive code.
- Easy configuration of security attributes and options.
- Smooth cross-browser compatibility.
4. Security and Privacy Measures
Cookies should always be used with proper
security settings and privacy protection.
Key security practices
- Use HTTPS and the Secure attribute: Prevents data interception.
- Set the SameSite attribute: Protects against CSRF attacks.
- Use the HttpOnly attribute: Mitigates XSS attacks (server-side configuration).
Key privacy practices
- Do not store personal information: Store only IDs or tokens and manage actual data on the server.
- Comply with regulations: Implement consent management in accordance with GDPR and related laws.
- Encrypt sensitive data: Always encrypt critical information before storage.
5. Verifying and Debugging Cookies
Using developer tools helps you efficiently verify and debug cookie behavior.
Browser-specific tools
- Google Chrome: Highly functional and user-friendly interface.
- Firefox: Advanced storage management features.
- Edge and Safari: Managed using similar steps to Chrome.
Using the JavaScript console
console.log(document.cookie);This allows for quick testing and debugging.
6. Practical Best Practices
Below are concrete recommendations for safe and efficient cookie management:
- Store only the minimum required data Avoid unnecessary cookies and manage critical data on the server.
- Set appropriate expiration periods Use short expiration times and delete unused cookies.
- Strengthen security settings Always configure Secure, HttpOnly, and SameSite attributes.
- Obtain user consent Deploy a consent banner that complies with GDPR and other privacy regulations.
- Use debugging tools effectively Regularly inspect cookies using browser developer tools.
- Leverage third-party libraries Use libraries such as js-cookie to simplify management and improve readability.
Conclusion
This article provided a comprehensive overview of cookie management in JavaScript,
covering everything from basic usage to security and privacy considerations.
Key takeaways
- The fundamentals of how cookies work and when to use them.
- How to set, retrieve, and delete cookies using JavaScript.
- The importance of security measures and legal compliance.
- Efficient workflows using developer tools and third-party libraries.
Next steps
Use this guide as a reference to implement cookie management in real-world projects.
To stay secure and compliant with evolving privacy laws,
continuous learning and regular reviews of best practices are essential.
Keep incorporating new technologies and knowledge to build safer,
more user-friendly web applications.



