Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting user cookie

I want to create and persist cookies to store some user info -- i.e. some of their preferences, their avatars, etc. I want these cookies to stay on user's computer till they're removed -- either by users or my app.

I use Facebook/Google authentication in my ASP.NET MVC app so I already use cookies but they expire when user ends his/her session.

What is the right approach to doing what I want to do? I can think of two approaches:

  1. Do not expire the cookie but change a value in it to indicate that the user's session has expired.
  2. Create another cookie with a different name that stores user info/preferences.

I wanted to see how others handled this.

like image 719
Sam Avatar asked Nov 30 '25 23:11

Sam


1 Answers

You can create extremely long expiring cookies, but this isn't the best way to store persistent user information on user browser.

For example, cookie is limited to 4096 bytes, not so much if you want to store images (user avatars). Also, cookies goes up and down along your connection always, no matter if you want to access them or not -> waste of bandwith.

If you're developing a strong client-side application may I humbly suggest you to use the Local Storage? The support is more o less ubiquitous (http://caniuse.com/#search=localstorage), it will persist until removed, and it doesn't suffer for all the problems that cookies have.

I suggest you to check this SO answer (Local Storage vs Cookies) for more details about cookie vs localstorage.

If you need a couple of samples of local storage usage, you can check this link (https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage). For example:

   function setInfo(key, data) {
    if (!window.localStorage) {
        window.localStorage.setItem(key, data);
    } else {
        console.log('Local Storage: not supported');
    }
}
like image 62
Luca Ghersi Avatar answered Dec 04 '25 11:12

Luca Ghersi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!