Skip to main content
Practice

Cookies

Cookies are small pieces of data stored by a website in the user's browser.

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


Key Features of Cookies

  • Expiration: Cookies can have an expiration date. Once this date is reached, the cookie is automatically deleted.

  • Domain and Path Restriction: Cookies can be restricted to be used only for specific domains and paths.

  • Security: Options like HttpOnly and Secure can prevent cookies from being stolen and exposing personal information. HttpOnly prevents JavaScript from accessing the cookie, while Secure ensures cookies are only sent over HTTPS (secure connections).


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

This code

  • Sets a cookie named "username" with the value "John": username=John;

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

  • Accessible on all pages of the website: path=/.


Cookies are stored in document.cookie, which returns a string representing the cookies.

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

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

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

Cookies cannot be directly deleted by JavaScript. Instead, you can set the expiration date of the cookie to a past date, effectively expiring it.

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

By doing this, the "username" cookie is immediately deactivated.

The code on the right is an example of storing a cookie in the browser and checking the stored cookie.

Want to learn more?

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