3

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.

CBroe
  • 82,033
  • 9
  • 81
  • 132
Sam
  • 19,814
  • 35
  • 141
  • 272

1 Answers1

2

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');
    }
}
Luca Ghersi
  • 2,956
  • 18
  • 28
  • Thank you for your response. BTW, I didn't mean I would save the actual avatar image. Just the URL of avatar file. – Sam Mar 16 '16 at 15:22