JavaScript Cookies: How to Set, Get, and Delete Cookies

JavaScript cookies tutorial illustrating how to set, get, and delete browser cookies using document.cookie.

Post Date: April 26, 2025
Last Updated:
November 03, 2026

Introduction

JavaScript cookies are small pieces of data stored in a user’s web browser that help websites remember information between visits. They are commonly used to manage user sessions, store user preferences, remember login information, and provide a personalized browsing experience.

JavaScript provides the document.cookie property to create, retrieve, and delete cookies directly from the browser. Developers can also configure cookie attributes such as expiration dates, paths, domains, and security settings to control how cookies are stored and accessed.

Understanding how JavaScript cookies work is important for developers who want to manage browser data effectively and improve website functionality.

In this guide, you’ll learn how to set, get, and delete cookies using JavaScript, along with practical code examples, explanations, and important cookie security considerations.

What Are JavaScript Cookies?

Cookies are small key-value pairs that websites store in a user’s browser. They allow websites to remember information between HTTP requests because HTTP is a stateless protocol.

Whenever a browser sends a request to a website, matching cookies can automatically be included in the request headers.

JavaScript cookies are commonly used for:

  • User sessions: Maintaining session-related information.
  • User preferences: Remembering language, theme, and display settings.
  • Login functionality: Supporting authentication workflows when appropriately configured.
  • Shopping carts: Remembering cart-related information.
  • Website functionality: Maintaining useful information between page visits.

A cookie consists of a name and value, along with optional attributes that control its expiration, availability, and security.

Example:

document.cookie = "username=Sujith; path=/";

In this example:

  • username is the cookie name.
  • Sujith is the cookie value.
  • path=/ makes the cookie available throughout the website.

Setting Cookies with JavaScript

You can create a cookie in JavaScript by assigning a string to the document.cookie property.

A cookie can include additional attributes such as expires, max-age, path, and domain to control its lifetime and availability.

The following function creates a cookie named username and sets its expiration date to seven days.

JavaScript set cookie example demonstrating how to create a username cookie with a seven-day expiration using document.cookie.

Explanation

  1. new Date() creates a new JavaScript date object.
  2. setTime() calculates the expiration time by adding seven days.
  3. toUTCString() converts the expiration date into the required UTC string format.
  4. document.cookie creates the cookie with its name, value, expiration date, and path.
  5. alert() displays a confirmation message.

The cookie remains available until its expiration date unless it is deleted earlier.

You can also use the max-age attribute to specify how long a cookie should remain valid in seconds.

document.cookie = "username=Sujith; max-age=604800; path=/";

Here, 604800 represents seven days in seconds.

Using max-age is a convenient alternative when you want to specify a cookie’s lifetime without calculating an expiration date.

Getting Cookies with JavaScript

You can retrieve cookies using the document.cookie property. It returns all cookies accessible to the current document as a semicolon-separated string.

When a website contains multiple cookies, you can split the returned string and search for a specific cookie by its name.

JavaScript get cookie example showing how to retrieve a specific username cookie using document.cookie and display its value in the browser.
JavaScript get cookie example showing how to retrieve a specific username cookie using document.cookie and display its value in the browser.

Explanation

  1. name + "=" creates the cookie name pattern to search for.
  2. document.cookie.split(";") separates all accessible cookies.
  3. The for loop checks each cookie individually.
  4. trim() removes unnecessary spaces.
  5. startsWith() checks whether the cookie matches the requested name.
  6. substring() extracts and returns the cookie value.
  7. If the cookie does not exist, the function returns null.

For example, if the username cookie contains Sujith, the browser console displays:

Sujith

This method allows you to retrieve individual cookie values without manually checking the entire cookie string.

Deleting Cookies with JavaScript

You can delete a cookie in JavaScript by setting its expiration date to a time in the past or setting its max-age attribute to zero.

When deleting a cookie, make sure to use the same path and domain attributes that were used when creating it. Otherwise, the browser may not delete the intended cookie.

JavaScript delete cookie example demonstrating how to remove a username cookie by setting its expiration date to a past date using document.cookie.
JavaScript delete cookie example demonstrating how to remove a username cookie by setting its expiration date to a past date using document.cookie.

Explanation

  1. username= assigns an empty value to the cookie.
  2. max-age=0 instructs the browser to delete the cookie immediately.
  3. path=/ specifies the cookie path used when creating it.
  4. alert() displays a confirmation message.

You can also delete a cookie using an expiration date in the past.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

Both approaches can be used to remove cookies, provided the original path and domain settings match.

Full Example: Set, Get, and Delete Cookies Using JavaScript

The following complete example combines all three operations into one JavaScript implementation. You can use it to create a cookie, retrieve its value, and delete it.

JavaScript Code

Complete JavaScript cookies code example showing how to set, retrieve, and delete a username cookie using document.cookie, with browser developer tools displaying cookie informatio

How to Use the Example

  1. Call setCookies() to create a cookie named username.
  2. Call getCookie("username") to retrieve the stored username.
  3. Check the returned value in the browser console.
  4. Call deleteCookies() to remove the cookie.

You can test these functions in your browser’s developer console.

JavaScript cookies support several attributes that control their storage, accessibility, lifetime, and security.

AttributeDescription
expiresSpecifies the date and time when the cookie expires.
max-ageDefines the cookie lifetime in seconds.
pathSpecifies the URL path where the cookie is available.
domainDefines the domain that can access the cookie.
secureSends the cookie only over HTTPS connections.
samesiteControls whether cookies are sent with cross-site requests.
httponlyPrevents JavaScript from accessing the cookie. It must be configured by the server.

When working with JavaScript cookies, security should always be considered.

  • Use the Secure attribute to restrict cookies to HTTPS connections.
  • Configure SameSite appropriately to help protect against cross-site request forgery (CSRF).
  • Use HttpOnly for authentication cookies to prevent JavaScript access.
  • Avoid storing passwords, authentication secrets, or sensitive personal information in JavaScript-accessible cookies.
  • Set appropriate expiration dates to avoid keeping cookies longer than necessary.
  • Use appropriate cookie consent mechanisms when required by applicable privacy regulations.

Important: Cookies created using JavaScript cannot be assigned the HttpOnly attribute. This attribute must be configured through an HTTP response from the server.

Frequently Asked Questions (FAQs)

You can set a cookie using the document.cookie property. Specify the cookie name, value, and optional attributes such as expiration date and path.

Example:

document.cookie = "username=Sujith; max-age=604800; path=/";

This creates a cookie that remains valid for seven days.

You can retrieve a specific cookie by accessing document.cookie, splitting the returned string, and searching for the required cookie name.

Example:

function getCookie(name) {
    const cookies = document.cookie.split(";");

    for (let cookie of cookies) {
        cookie = cookie.trim();

        if (cookie.startsWith(name + "=")) {
            return cookie.substring(name.length + 1);
        }
    }

    return null;
}

console.log(getCookie("username"));

The function returns the cookie value if it exists; otherwise, it returns null.

You can delete a cookie by setting its max-age attribute to zero or assigning an expiration date in the past.

Example:

document.cookie = "username=; max-age=0; path=/";

Ensure that the path and domain attributes match the original cookie settings so the correct cookie is removed.

Conclusion

JavaScript cookies provide a simple and effective way to store and manage small amounts of information in a user’s browser. By using the document.cookie property, developers can create cookies with expiration dates, retrieve stored values, and delete cookies when they are no longer needed.

Understanding how to set, get, and delete cookies helps developers manage user preferences, maintain website sessions, and improve the overall browsing experience.

Always configure cookies with appropriate security attributes and avoid storing sensitive information in cookies that can be accessed through JavaScript. Following these practices helps developers build more secure, reliable, and user-friendly web applications.

Need Help with JavaScript Development

Looking for reliable JavaScript development, web application security, or software development solutions?

Pheonix Solutions provides technology services covering software development, application security, cloud infrastructure, DevOps, and technical support.

Our experts can help you build secure web applications, implement effective authentication mechanisms, and maintain reliable software systems.

Explore our Software Development Services to learn more.

Need assistance with your project? Contact our experts to discuss your requirements.

sujith k

Writes about Web & Architecture at Pheonix Solutions.

Leave a Comment

Scroll to Top