Recently, I was tasked with a question during an interview with a big company. The question was, “Tell me the difference between cookies and localStorage?” And although I had a very broad idea of what the differences might be, I thought I’d dive into this topic a bit more.
Introduction to Cookies
So what are cookies? Well, I can most certainly tell you they’re not what you might find in your snack stash when you’re craving some sugary sweets. In fact, cookies are small files which are located on a user’s computer. They are designed to hold a generous amount of data specific to a client and website, and they can accessed either by the web server or the client computer. The reason behind this is to allow the server to deliver a page tailored to a particular user, or the page itself can contain some script which knows of the data in the cookie, and therefore it is able to carry information from one visit to the website to the next.
So what does a cookie contain? Well each cookie is effectively a small lookup table containing pairs of key, data values. Once the cookie has been read by the code on the server or the client computer, the data can be retrieved and used to customize the web the web page appropriately.
Cookies are pretty much a convenient way to carry information from one session on a website to another, or between sessions on related websites, without having to burden a server machine with massive amounts of data storage. If we were to store data on the server without using cookies, then it would be difficult to retrieve a particular user’s information without requiring a login on each visit to the website. Therefore, a cookie can simply be used if there is a large amount of information to store. In addition a cookie can be made to persist for an arbitrary length of time.
Introduction to localStorage
Differences between cookies and localStorage
Cookies and local storage serve different purposes. Cookies are mainly for reading server-side, whereas local storage can only be read by the client-side. Apart from saving data, a big technical difference is the size of data you can store, and as I mentioned earlier localStorage gives you more to work with. In conclusion, the question when dealing with the two, one should ask is, in your application who needs this data- the client or the server?