Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to store JSON object in cookie? [closed]

I have following object.

position = {
    latitude: 19.067863700000004,
    longitude: 72.9991898,
    pincode: 400701
}

I want to store value of latitude, longitude and pincode in cookie.

I know three ways.

i) store entire position object in cookie.(which is not recommended according to this)

var pos = JSON.stringify(position);
document.cookie = "position=" + pos;

ii) create three cookie latitude, longitude and pincode and store respective value in respective cookie.

document.cookie = "latitude=" + position.latitude;
document.cookie = "longitude=" + position.longitude;
document.cookie = "pincode=" + position.pincode;

iii) create one cookie position and store value in this cookie is 19.067863700000004|72.9991898|400701

var pos = position.latitude + "|" + position.longitude + "|" + position.pincode;
document.cookie = "position=" + pos;

My question is which is best/ideal way to store cookie?(Give a reason if possible)

like image 215
yajiv Avatar asked Jul 04 '18 11:07

yajiv


2 Answers

For that small object, I would definitely put it in the cookie as JSON. Overhead when doing this will be almost none existent and definitely not an issue.

As for what generally works best it's highly dependant on what you have and what you wanna end up with.

Keep in mind:

  • It Will produce overhead (from JSON structure, additional characters) and w You don't wanna other apps overwriting your cookies with simple names like that.

  • Choose a better name with a prefix of a name like yourappname-something or some random longer string instead of the name.

  • Large and complex objects = you will have large cookies. One can easily go over the 4K size limit for cookies.

To solve last problem you can put minimal payload in each cookie but for a lot of data you will end up with a LOT of cookies and it's not as readable as one would like. If you object has nested objects name will begin to look like myapp-object-nested1-nested2-property. This can be hard to navigate and then put back together when you need a single object from cookies again.

You can go a mix of both approaches - restructuring large objects into COMPOSITION of smaller ones where it makes sense. This will land somewhere in between too large cookies and too many names for small cookies. Try to do it in a way so re assembly is readable and quick.

Another option altogether is local or session storage of a browser, the limit is much higher there so you can dump way bigger JSON directly.

like image 154
DanteTheSmith Avatar answered Oct 14 '22 06:10

DanteTheSmith


Well if you are concerned about security, it's better to use some one way cryptographic algorithms over original data so that someone with access to user's browser won't be able to read/understand the cookies.

like image 32
Amjad sibili Avatar answered Oct 14 '22 07:10

Amjad sibili