Usage of cookies:
Cookies are a very common type of storage mechanism for any webpage to store information that needs to exist even if user restart their browser or after it crash. Hence, these information is considered to be stateful.
Here are some of the common properties of a cookie (Maybe different based on browsers):
- Maximum size of 4KB or 4096 Bytes per cookie
- Maximum of 20 cookies per domain
For example is the storage of user information so that the user does not need to re-login even after they restart the application.
document.cookie = "userName=someNameA"; console.log(document.cookie); // Output: "userName=someNameA;" document.cookie = "userName=someNameBBB"; console.log(document.cookie); // Output: "userName=someNameBB;"
However, the above declaration will result in the cookie deleted when the browser closed. Thus, it is a good practice to add an expire date in UTC time. Let’s also add a path parameter to have the cookie to be use by all pages in this domain.
document.cookie = "userName=someNameA; expires=Wed, 10 Dec 2025 12:00:00 UTC; path=/";
To read the cookie, just assign it to a variable. But be careful that you will receive all the cookie that was set together. Hence, the processing after reading it need to be done carefully.
document.cookie = "userName=someNameA"; document.cookie = "userName1=someNameB"; let cookies = document.cookie; console.log(document.cookie); // Output: "userName=someNameA; userName1=someNameB;"
To delete a cookie or key value pair to be more exact, we will just need to set the expiry date to some date in the pass.
document.cookie = "userName=; expires=Thu, 01 Jan 1970 12:00:00 UTC; path=/";
No Responses Yet