One of the most popular myths in the web dev community is around cookies & local storage. It's also a commonly asked interview question. Let's uncover the concept behind these two storage mechanisms!
Cookies are small files that 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 be 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 that knows of the data in the cookie, and therefore it can carry information from one visit to the website to the next.
- Each cookie is effectively a small lookup table containing pairs of the key, data values.
- Cookies are primarily for reading server-side.
- Introduced before HTML5.
- Has an expiration date.
- Cleared by JS or by Clear Browsing Data of browser or after expiration date.
- Will be sent to the server per each request.
- The capacity is 4KB.
- Only strings can be stored in cookies.
- There are two types of cookies: persistent and session.
- Each domain stores all its cookies in a single string, which can make parsing data difficult.
- Data is unencrypted, which becomes an issue because though small in size, cookies are sent with every HTTP request.
- SQL injection can be performed from a cookie.
- If we have unnecessary cookies, they will be sent with all the requests and responses and hence slow down the application.
- Local Storage is as big as 5MB per domain.
- Local storage can only be read by the client-side.
- Introduced with HTML5.
- Does not has an expiration date.
- Cleared by JS or by Clear Browsing Data of the browser.
- You can select when the data must be sent to the server.
- Data is stored indefinitely and must be a string.
- Only have one type.
- Support by most modern browsers
- Same-origin rules apply to local storage data
localStorage will not be available if you switch from 'HTTP' to 'HTTPS' secured protocol, where the cookie will still be accessible.
- Data once stored is persistent. It is the duty of the application to clean data after use.
- Data stored in localStorage is not secured. Never store sensitive information to localStorage.
Find more information about cookies and local storage on the links below:
If you found this article insightful and helpful, then do let me know your views in the comments. In case you want to connect with me, follow the links below: