Skip to main content
Practice

Cookies

Cookies are small pieces of data that a website stores on a user's browser.

Cookies are used for various purposes, such as saving user preferences or keeping track of pages visited by the user.


Key Features of Cookies

  • Expiration date: Cookies can have an expiration date. After this date, the cookie will be automatically deleted.

  • Domain and Path restrictions: Cookies can be restricted to a specific domain and path.

  • Security: By using the HttpOnly and Secure options, we can prevent the exposure of personal information due to cookie theft. HttpOnly prevents JavaScript from accessing the cookies, and Secure ensures cookies are only sent over HTTPS (secured) websites.


JavaScript
document.cookie =
'username=John; expires=Fri, 31 Dec 2023 12:00:00 UTC; path=/'; // setting cookie

This code

  • Sets a cookie with the name "username" and stores the value "John": username=John;

  • This cookie is valid until December 31, 2023: expires=Fri, 31 Dec 2023 12:00:00 UTC;

  • The cookie can be accessed on all pages of the website: path=/.


Getting a Value from Cookies

Cookies are stored in document.cookie. The document.cookie returns a string representing all cookies.

JavaScript
function getCookie(name) {
const value = '; ' + document.cookie; // Cookie values are separated by semicolons
const parts = value.split('; ' + name + '='); // Find the cookie by name

if (parts.length == 2) return parts.pop().split(';').shift(); // Return the cookie value
}

console.log(getCookie('username')); // John

Cookies cannot be directly deleted with JavaScript. Instead, we can expire a cookie by setting its expiration date to a past date.

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

Setting the cookie like this will immediately deactivate the "username" cookie.

The right code example shows how cookies are stored on the browser and how to check the stored cookies.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.