Summary
Cookies are sent with HTTP requests and can be secured with flags. LocalStorage and SessionStorage are browser-only key-value stores accessible to JavaScript.
Interview Points
- Cookies can be
HttpOnly,Secure, andSameSite. - LocalStorage persists until cleared and is accessible to JavaScript.
- SessionStorage is scoped to a tab/session.
- Avoid storing sensitive tokens in JavaScript-accessible storage when XSS risk matters.
- Cookies need CSRF protection depending on SameSite and auth model.
2-3 Minute Interview Script
“Cookies, LocalStorage, and SessionStorage are all browser storage options, but they have different security and lifecycle behavior.
Cookies are automatically sent with matching requests. With
HttpOnly, JavaScript cannot read them, which helps protect tokens from XSS.Securerequires HTTPS, andSameSitehelps reduce CSRF risk.LocalStorage is easy to use and persistent, but JavaScript can read it, so an XSS bug can expose anything stored there. SessionStorage is similar but scoped to a browser tab.
In an interview, I would say for sensitive session credentials I usually prefer secure, HttpOnly, SameSite cookies, while LocalStorage is better for non-sensitive preferences or cached UI state.”
Follow-Ups
- How does SameSite help with CSRF?
- Why is XSS relevant to token storage?