Sometimes, we want to set a cookie to expire in 1 hour in JavaScript.
In this article, we’ll look at how to set a cookie to expire in 1 hour in JavaScript.
How to set a cookie to expire in 1 hour in JavaScript?
To set a cookie to expire in 1 hour in JavaScript, we set the expires
parameter on the cookie.
For instance, we write
const now = new Date();
const time = now.getTime() + 3600 * 1000;
now.setTime(time);
document.cookie =
"username=" + value + "; expires=" + now.toUTCString() + "; path=/";
to get the current datetime with the Date
constructor.
Then we get its timestamp in milliseconds with getTime
and add 3600 seconds to it.
3600 seconds is an hour.
Then we call setTime
to set time
as its new timestamp.
Next, we set document.cookie
to a string that includes expires=" + now.toUTCString()
to set the expiry date of the cookie to an hour.
Conclusion
To set a cookie to expire in 1 hour in JavaScript, we set the expires
parameter on the cookie.