set value in cookies in javascript

To set a value in cookies using JavaScript, you can use the document.cookie property. You should set the name, value, and expiry date of the cookie.

Here is an example code to set a cookie:

index.tsx
// set the cookie name, value and expiry date
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/";

// output the cookies
console.log(document.cookie);
185 chars
6 lines

In this example, we set a cookie named username with a value of John Doe. We also set an expiry date of Thu, 18 Dec 2022 12:00:00 UTC, which is when the cookie will expire. Finally, we set the cookie path to /, which means that the cookie is available for all pages on the website.

You can retrieve and update this cookie later using the same document.cookie property.

gistlibby LogSnag