본문으로 건너뛰기

Cookies

Cookies

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

Websites use cookies to remember users or to store information such as user preferences.


Key Features

  • Expiration limit: Cookies can have an 'expiration date' set. Once this date has passed, the cookie is automatically deleted.

  • Domain and path restrictions: Cookies can be restricted for use only within a specific domain and path.

  • Security: Options like HttpOnly or Secure can be used to prevent exposure of personal information due to cookie theft.


Setting Cookies

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

This code sets a cookie named "username" with the value "John". This cookie is valid until December 31, 2023, and can be accessed from any page of the website.

Getting Values from Cookies

JavaScript
function getCookie(name) {
let value = '; ' + document.cookie; // Cookies are separated by semicolons.
let 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

This function returns the value of the given cookie name.

Deleting Cookies

You cannot directly delete a cookie in JavaScript. Instead, you set the expiration date of the cookie to the past to expire it.

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

By setting it this way, the "username" cookie is immediately deleted.

The code on the right is an example of how to store cookies in the browser and verify the stored cookies.