DEV Community

Archit Sharma
Archit Sharma

Posted on

6 1 1 1 1

Working with Cookies in JavaScript🍪

1. Test if cookies are enabled

If you want to check whether cookies are enabled before using them, you can use navigator.cookieEnabled:

if (navigator.cookieEnabled === false)
{
 alert("Warning: Cookies are not enabled in your browser!");
}

Enter fullscreen mode Exit fullscreen mode

Note that on older browsers navigator.cookieEnabled may not exist, so in that case you won't detect that cookies are not enabled.

2. Adding and Setting Cookies

Cookies are saved in name-value pairs : username = Jack
To simply create a cookie you can use document.cookie property

You can also add an expiry date (in UTC time) and a path parameter, you can tell the browser what path the cookie belongs to.

Here is an example setup:

// Define cookie properties
const COOKIE_NAME = "ExampleCookie";   // The cookie's name
const COOKIE_VALUE = "Hello, Cookie!";  // The cookie's value
const COOKIE_PATH = "/example/jack";       // The cookie's path

// Calculate the expiration time (1 minute in the future)
const expirationTime = new Date(Date.now() + 60000); // 60000ms = 1 minute

// Format expiration time to UTC string
const COOKIE_EXPIRES = expirationTime.toUTCString();

// Set the cookie with the defined properties
document.cookie = `${COOKIE_NAME}=${COOKIE_VALUE}; expires=${COOKIE_EXPIRES}; path=${COOKIE_PATH}`;

Enter fullscreen mode Exit fullscreen mode

3. Reading Cookies

To read cookies document.cookie property will return all cookies in one string like: cookie1=value; cookie2=value; cookie3=value;

4. Removing Cookies

To remove a cookie, you don't have to specify a cookie value. Just set the expires parameter to a past date:

document.cookie = `${COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${COOKIE_PATH};`;
Enter fullscreen mode Exit fullscreen mode

If you found this useful, consider:

✅ Follow @iarchitsharma for more content like this
✅ Follow me on Twitter

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay