How to Set cookie and get cookie with JavaScript?
Cookie in JavaScript
357
19-Jul-2021
Updated on 29-Nov-2023
Aryan Kumar
29-Nov-2023In JavaScript, cookies are small pieces of data stored on the client-side (in the user's browser). They are commonly used to store information about the user or their preferences. Here's how you can work with cookies in JavaScript:
Setting a Cookie:
You can set a cookie using the document.cookie property. Here's an example:
Reading a Cookie:
To read a cookie, you can use the document.cookie property or create a function to get a specific cookie value by name (as shown in the previous response):
Deleting a Cookie:
To delete a cookie, you can set its expiration date to a date in the past:
Remember that cookies are limited in size and are sent with every HTTP request, so it's important to use them judiciously and consider other storage options (like Local Storage or Session Storage) for larger amounts of data.