1

I've got an web app that needs to store some non-sensitive preferences for the user. Right now I'm storing their language preference and what mode they want a window opened in by default in two cookies:

  • "lang" can be "en" or "de"
  • "mode" can be "design" or "view"

I might add a few more in the future. I'm not sure how many, but probably never more than a dozen.

Language is parsed on every request, whereas the mode cookie is only used occasionally. I saw a recommendation that made sense I shouldn't try to do what I was originally planning to do and strongly type a user settings class deserialized on each request because of the overhead involved.

I see three options here and I'm not sure which is the best overall.

  • Keep things as they are, add a new cookie for each new setting
  • Combine the cookies into a single settings cookie and add future values to it
  • Change the mode cookie to settings (leaving language alone), add new user settings values to the settings cookie

All would work obviously. I'm leaning toward option three, but I'm not sure if there's a best practice for this?

2 Answers 2

1

Good question.

I don't know of any standard in dealing with cookies. I know what works for me. It might vary from platform to platform. Keep in mind that data stored in cookies is visible to anyone.

I always encrypt cookies, even if the data is not important. The encryption ensures the integrity of the cookie. A malicious person can not tell how I am using the cookie. If the cookie is tampered with, it will fail decryption. I typically serialize, with JSON, a class into the cookie. This keeps the data structured and enables an easy way to read and write data to and from the cookie. Depending on browsers and servers there are limitations. It's important to keep cookie data to a minimum. The smaller the better.

1
  • Not sure why, but I hadn't even considered using JSON for cookies.
    – Paul
    Commented Nov 20, 2012 at 20:20
1

The typical approach is to only store a unique session id with the cookie. No need to store anything other than that on the client side. On the server side you'd associate data with that key. Typically that means a session information table that has at least two columns: the session id and session data. Session data often is comprised of some serialized data structure (in php, an array, for example). On the page load, after reading the session id from the request, load and unserialize the session data from the database (or storage system of your choice). When the request ends, save it back to the database.

1
  • Yeah that's true, and a lot of user data is already stored there.
    – Paul
    Commented Nov 20, 2012 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.