What are the differences between LocalStorage, SessionStorage, and Cookies? When should you use each of them?

As a software developer, you have definitely heard of and used LocalStorage, SessionStorage, and Cookies. But what is the difference between them, and when should you use which one? Let's explain it in simple terms.
1) LocalStorage: This is permanent client-side storage. Its data is never sent to the server automatically. The reason it is called permanent storage is that its data remains stored until you manually delete it.
When should you use it?
For data that the browser should always remember and that does not need to be sent to the server. For example: the website's dark or light theme ("theme", "dark"), language ("lang", "en"), etc.
2) SessionStorage: This is tab-based temporary client-side storage. Its data is also never sent to the server automatically. When you close your browser tab, or close the browser itself, its data is deleted. Also, even if you have a session in one tab, that session will not be available if you open another tab.
When should you use it? For data that should not always remain in the browser for security or temporary-use reasons and does not need to be sent to the server. For example: multi-step form draft data, a pop-up message that you want to show the user only once per session, etc.
3) Cookies: These can communicate with both the client and the server. However, there is a catch. Cookies have some special security capabilities. When certain flags are enabled, their data cannot be read by browser JavaScript. Cookies are commonly used to provide security from the server side. When the server sets a Cookie, if the HttpOnly flag is enabled, its data cannot be read by browser JavaScript. This helps prevent someone from stealing your token through browser JavaScript and causing harm. You can also set an expiration period (Max-Age) for Cookies, so that the specific cookie data is automatically removed after that specified period.
When should you use it? For data that needs to be verified by the server with every request from the browser. For example: a user can perform certain actions only if they are logged in, or a user can access the admin panel only if they are an admin, etc.
Ultimate Summary
LocalStorage and SessionStorage are pure client-side storage. They have no direct relationship with the server. The main difference between them is their persistence. On the other hand, Cookies can communicate with both the client and the server, but when the HttpOnly flag is enabled, they cannot be read by browser JavaScript.



