Why are there no builtin JS functions for cookies? [closed]


Okay, this question might sound absurd, but why are there no implementation to modify cookies through JS. I ask this because over the web, I've seen some quite horrible implementations to manipulate cookies.

Also, why is cookie not represented as an Object? It seems to me if cookie was represented as an object, it would've been far far easier to manipulate it. Then document.cookie can just be a string representation of the object.

document.cookie, even if it sounds like a simple property, hides in fact function accesses (a getter and a setter).

Why isn't the cookie a whole structured object ? I guess the reasons are:

  • the same than for localStorage : to force you set only very light data, in order to not make the cookies heavy on disk
  • standard usage both on server, client, and in-between (ie transmission)
  • easy normalization process...

To answer to comments :

  • I don't say it was right : I see some reasons
  • I suppose the localStorage API is the logical successor, a little better (still not perfect)

document.cookie is the way it is because that's how it was first implemented. It's a crap reason, I know, but you have to remember the history of the early web. The first browser to implement a new feature set the standard for all other browsers to copy.

It's the exact same reason that null == undefined in JavaScript. Old bugs become required implementation details, and we'll be stuck with it forever, or until next week, depending on who's actively working on the w3 specifications.

Why are there no implementation to modify cookies through JS?

Because it wouldn't be backwards compatible. Obviously we can't change the existing implementation, so we'd have to create a new one. In creating a new one we'd want to create one that can be reasonably replicated by existing JS code to back-fill old browsers, but if we've got to add a polyfill to get it working anyway, why bother even adding the new feature to the browser?

So, we're never gonna see a better cookie right?

wrong. Browsers are adding a new object implementation to store data locally, it's called localStorage, and it can be reasonably replicated by cookies where it needs to be. This also allows us to separate the local information from the server information (servers can set HTTP only on cookies for server-only cookies).