TechnicalEasy HTTP & REST APIs
What is the difference between cookies, localStorage and sessionStorage?
Asked for Frontend Developer, Full-Stack Developer
Why they ask this: Choosing where to store tokens and preferences affects both security and user experience.
Answer
| Cookies | localStorage | sessionStorage | |
|---|---|---|---|
| Size | about 4 KB each | about 5 MB | about 5 MB |
| Sent to the server automatically | yes, with every matching request | no | no |
| Lifetime | until Expires/Max-Age, or the session | until cleared | until the tab closes |
| Readable by JavaScript | unless HttpOnly | yes | yes |
Security notes:
- Store auth tokens in
HttpOnly,Secure,SameSitecookies where possible, so an XSS attack cannot read them. - Anything in
localStoragecan be stolen by any script running on the page. - Use
localStoragefor non-sensitive preferences such as the theme or a saved filter.
Can you explain this in your own words?