Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Cookie + ReactJS: How to set expiration time for a cookie?

In my ReactJS project, currently I am saving the cookie like cookie.save('token', received_token, { path: '/'} ); and retrieving it from the local storage like so: cookie.load('token');.

So I was wondering, is a way to set expiration time when .save() the token received, and once expired, automatically have it remove itself from the local storage?

Thank you and will accept the answer with vote up.

like image 209
Walter Avatar asked Oct 25 '16 00:10

Walter


People also ask

How do you set the expiry period for a cookie object?

Just set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.

How do you set cookies to expire in 30 days?

Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes). The path on the server in which the cookie will be available on.

What is cookie expiration time?

A temporary cookie expires when a web browser session ends – usually, this happens when the browser program is closed down. This is a session cookie. The cookie's data is not stored on your computer permanently. The data in a persistent cookie is stored on your computer for a specified time period.


1 Answers

You can pass maxAge or expires in options as 3rd parameter in cookie.save function

Syntax:

reactCookie.save(name, val, [opt])

Example:

// maxAge Example
reactCookie.save("token", "token-value", {
   maxAge: 3600 // Will expire after 1hr (value is in number of sec.)
});

// Expires Example
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

reactCookie.save("token", "token-value", {
   expires: tomorrow // Will expire after 24hr from setting (value is in Date object)
});

Documentation: https://github.com/eXon/react-cookie#reactcookiesetrawcookiecookies

like image 85
jad-panda Avatar answered Sep 28 '22 19:09

jad-panda