<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by M S on Medium]]></title>
        <description><![CDATA[Stories by M S on Medium]]></description>
        <link>https://medium.com/@shetty.man?source=rss-23a313452b90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by M S on Medium</title>
            <link>https://medium.com/@shetty.man?source=rss-23a313452b90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:08:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shetty.man/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Browser Storage Interview Questions: The Answers That Land]]></title>
            <link>https://medium.com/@shetty.man/browser-storage-interview-questions-the-answers-that-land-c7ff71f57b59?source=rss-23a313452b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7ff71f57b59</guid>
            <dc:creator><![CDATA[M S]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 15:10:10 GMT</pubDate>
            <atom:updated>2026-08-11T15:10:10.646Z</atom:updated>
            <content:encoded><![CDATA[<p>The interviewer asks where you’d store a session token, you say localStorage because it’s easy to read from JavaScript, and the conversation quietly ends there — not because the answer is wrong on a toy app, but because you just told them you don’t think about what happens when a script you didn’t write runs on your page. Browser storage questions are rarely about the API. They are a proxy for whether you reason about tradeoffs and blast radius.</p><h3>The three stores, and the one difference that matters</h3><p>Cookies, localStorage, and sessionStorage. A weak answer lists their size limits and lifetimes as trivia. A strong answer leads with the one behavioral difference the rest follows from: cookies are attached to every matching request automatically, and the other two are never sent unless your code puts them on the wire. That is why cookies own session identity, why a bloated cookie taxes every request to the origin, and why localStorage is the wrong place for anything the server needs to trust.</p><p>Get the lifetimes right because interviewers use them to check precision. A cookie with no Expires or Max-Age dies with the browser process, not the tab — people conflate the two constantly. localStorage persists until code, the user, or browser eviction under storage pressure clears it, which means treating it as durable is a bug waiting for a low-disk device to find. sessionStorage dies with the tab, survives a refresh, and a tab opened via window.open inherits a one-time snapshot copy of the opener’s sessionStorage that then diverges. That last detail is a power-user tell; most candidates never mention it.</p><h3>The question everyone gets wrong: HttpOnly vs SameSite</h3><p>These defend against opposite attacks, and treating them as interchangeable “cookie security” flags is the single most common way candidates fail the security portion. HttpOnly controls what a script on your page can read. SameSite controls what a request originating from another site can carry. If you say one when you mean the other, a sharp interviewer will stop and ask you to walk through an attack, and the confusion surfaces immediately.</p><p>Anchor the whole thing on blast radius. Assume XSS will happen — a compromised dependency or a stored payload. The question that decides how bad the day is: can the injected script read the session credential? If the token sits in localStorage, yes, in one synchronous line, and it exfiltrates to an attacker who replays it from anywhere for the full token lifetime. Put that on a 7-day “remember me” session and one XSS buys the attacker a week of portable, replayable access per victim. If the credential is an HttpOnly cookie, the script can still fire authenticated requests while it runs, but it cannot lift the token and keep using it after the tab closes. That is the argument, and it is an argument about limiting damage, not preventing XSS.</p><p>CSRF is the mirror image, and it is where SameSite earns its keep. The attacker reads nothing; they get the victim’s browser to send an authenticated request by abusing the automatic attachment that made cookies convenient — an auto-submitted form from evil.com, an img tag pointing at a state-changing endpoint. HttpOnly is irrelevant here because the cookie is attached, not read. The interviewer wants to hear layered defense: SameSite to stop the cross-site request from carrying the cookie at all, plus a server-side check (a CSRF token or an Origin / Sec-Fetch-Site assertion) for the cases SameSite does not cover, like a subdomain you do not fully trust.</p><h3>When to reach for Strict, Lax, or None</h3><p>Commit to a default and state the cost. Use Lax for session cookies; it sends the cookie on top-level GET navigation but not on cross-site POSTs, subresources, or iframes — exactly the shape of the classic CSRF form-submit, blocked, while a normal inbound link keeps working. Strict is tempting and usually wrong: it drops the cookie even on a top-level navigation from an external link, so a user clicking your link in an email lands logged out and files a support ticket. None re-enables full cross-site sending but the browser now rejects it unless it is paired with Secure. If a candidate can name the 2020 Chrome flip — when the unspecified default changed from None to Lax and broke a wave of embeds that had silently relied on send-everywhere — that is senior-level recall. The lesson was not “add SameSite=None”; it was that an embed depending on third-party cookies was already living on borrowed time.</p><h3>Design questions: where each thing actually goes</h3><p>Auth has the least room for taste. The session credential goes in a __Host-, HttpOnly, Secure, SameSite=Lax cookie, and the SPA stops trying to read it — which forces you to either proxy API calls through your own origin or accept cookie-based auth with the CSRF handling that follows. For “remember me,” the strong answer separates concerns: a short-lived session cookie plus a longer-lived refresh token cookie, the refresh token rotated on every use and stored only as a hash server-side so you can enumerate and revoke sessions. A stolen refresh token used a second time then surfaces as a rotation mismatch you can alarm on. Interviewers listen for whether you treat this as an auth-design problem, not a storage problem.</p><p>For a multi-step checkout, the line that separates senior from mid is “state belongs on the server, keyed by the cart ID in a cookie; the client copy is a cache you are allowed to lose.” Split the client side by lifetime: localStorage for a cart that should survive a refresh or a return visit, sessionStorage for in-progress fields that should die with the tab so a shared machine does not leak them. Then the hard line, unprompted: payment card data never touches any client store, not even transiently, because the moment it lands in your JS heap your PCI scope expands to that origin and every script on it. Send it straight to the processor’s tokenized iframe. That is a compliance constraint, not a preference, and naming it is a strong signal.</p><p>For cross-tab coordination — log out here, log out everywhere — reaching for a polling interval is a tell that you missed the primitive. Use BroadcastChannel for same-origin pub/sub. The storage event is the fallback for older targets, with one edge that trips people: it fires in other tabs, not the one that made the change, so the tab that triggered the logout has to act locally as well. Neither survives across origins, and a tab that was closed during the broadcast simply reconciles from the server on next load — which is the behavior you want anyway.</p><h3>The forward-looking question: third-party cookies</h3><p>Bringing this up unprompted is what moves an answer from strong to exceptional. Chrome’s third-party cookie deprecation — repeatedly delayed, directionally certain — kills the pattern where an embedded widget in a cross-site iframe reads its own cookies. Two replacements are worth naming. CHIPS (Cookies Having Independent Partitioned State) lets an embed opt into a cookie partitioned by the top-level site, so state persists but is siloed per embedding site. Privacy Sandbox replaces the measurement and interest-signal use cases that ad and analytics code was abusing cookies for. If you ship an embeddable SDK, the design answer is to assume the shared-cookie path is gone and build for partitioned or first-party-proxied state now.</p><h3>The tells an interviewer is actually grading</h3><p>Underneath every question is a small set of signals. The answers that land share a shape: they frame security as blast radius, they discuss tradeoffs instead of absolutes, they volunteer the third-party-cookie shift before being asked, and they reach for the storage event or BroadcastChannel the moment cross-tab sync comes up. The ones that stall have their own shape too, and any single one of these will sink an otherwise decent conversation:</p><p>Claiming HttpOnly protects against CSRF, or that SameSite protects against XSS.</p><p>Confusing a session cookie with sessionStorage — different lifetime, different scope, different failure modes.</p><p>Suggesting passwords or card numbers live in any client-side store, encrypted or not.</p><p>Waving at “encryption” as if it solves client-side secret storage, when the key has to live somewhere the same script can read.</p><p>The single most useful thing you can do before an interview is pick one real decision you made — a token you moved out of localStorage, a SameSite value that broke a login flow, a cart that lost state on refresh — and be ready to walk it end to end: what you assumed, what broke, what the symptom looked like, and what you would do differently. A concrete war story with a wrong turn in it outperforms a flawless recitation of the spec every time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7ff71f57b59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookies, localStorage, and sessionStorage: A Practical Guide to Browser Storage and Its Security…]]></title>
            <link>https://medium.com/@shetty.man/cookies-localstorage-and-sessionstorage-a-practical-guide-to-browser-storage-and-its-security-a43376760746?source=rss-23a313452b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43376760746</guid>
            <dc:creator><![CDATA[M S]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 14:04:33 GMT</pubDate>
            <atom:updated>2026-08-11T14:04:33.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cookies, localStorage, and sessionStorage: A Practical Guide to Browser Storage and Its Security Tradeoffs</h3><p>A session token sits in localStorage because the SPA needed to read it from JavaScript to attach an Authorization header, and eight months later a compromised analytics snippet reads that same token and ships it to an attacker who replays it for the full token lifetime. That single decision — where the credential lives — is the one most likely to turn a contained XSS bug into an account-takeover incident, and it gets made early, by whoever wired up auth, usually without the security review that a login page would get.</p><h3>Same API surface, three incompatible contracts</h3><p>The cookie contract is defined by one behavior: the browser attaches every matching cookie to every request for the domain, automatically, whether you wanted it on that request or not. That is why cookies own session identity, and also why the 4KB-per-cookie / roughly-50-per-domain budget matters more than it looks. Cookies ride on requests, so every kilobyte you park in one is a tax on every HTTP request to that origin, including the ones serving static assets from the same host. Put a 2KB JSON blob of “preferences” in a cookie and you have added 2KB to the header of every one of the ~1,200 requests/sec you serve at peak requests that never needed it. Lifetime is explicit via Expires/Max-Age; omit both and you get a session cookie tied to the browser process, which is not the same as the tab and surprises people who expect closing one tab to log them out.</p><p>localStorage and sessionStorage share an API and almost nothing else. The scope difference is the one that bites: localStorage is shared across every tab of the origin and survives restarts, while sessionStorage is per-tab and dies with the tab. The footgun is that a tab opened with window.open or target=_blank inherits a snapshot copy of the opener’s sessionStorage at creation time, then diverges — so “session” state silently forks, and the second tab acts on stale data. Both cap around 5 to 10MB and store strings only, which means every structured value costs a JSON.parse on read; do that on a hot render path with a large object and you will see it in a flame graph. And localStorage is not durable: under storage pressure the browser can evict an origin’s data with no event and no warning, so treating it as a cache you can lose is correct and treating it as a database is a bug waiting for a low-disk device to find it.</p><p>Reach for IndexedDB only when the data outgrows strings or the synchronous access starts blocking the main thread — structured records, Blobs, anything past a few hundred KB you query rather than dump. Below that threshold it is overhead: async plumbing and a schema for what a single localStorage key would have held.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUWpz_HT6J5_rnreRok4LA.jpeg" /><figcaption>The three main client-side stores compared on lifetime, scope, server transmission, and script visibility.</figcaption></figure><h3>HttpOnly and CSRF are not the same defense</h3><p>The mistake that shows up in code review is treating HttpOnly and SameSite as interchangeable “cookie security” flags. They defend against opposite attacks. HttpOnly is about what a script on your page can read; SameSite is about what a request from another site can carry. Ship one thinking it covers the other and you have a hole that passes every checklist that only asks “are the cookies secured?”</p><p>Take XSS as a given — assume that at some point a script you did not write runs on your origin, whether from a dependency, an ad tag, or a stored payload. The question that decides how bad that day is: can that script read the session credential? If the token is in localStorage, yes, in one synchronous line, and it exfiltrates to an attacker-controlled endpoint that replays it from anywhere for the full token TTL. If the credential is an HttpOnly cookie, no. The attacker can still fire authenticated requests from the victim’s browser while the payload runs, which is bad, but they cannot lift the credential and keep using it after the user closes the tab or the payload is scrubbed. That is the whole argument, and it is an argument about blast radius, not about preventing XSS. Concretely: with a token in localStorage and a 7-day lifetime, one XSS gives an attacker 7 days of portable, replayable access per victim; with HttpOnly, the window closes when the session does. So put session credentials in HttpOnly cookies. The cost is real: your SPA can no longer read the token to set an Authorization header, so you either proxy API calls through your own origin or accept cookie-based auth with the CSRF handling it forces — and that CSRF handling is not optional, which is the next problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4AaFzZXUBRwRmMgbi15ag.jpeg" /><figcaption>The same XSS foothold plays out very differently depending on where the token lives.</figcaption></figure><p>CSRF is the mirror image, and the reason cookie auth is not free. The attacker reads nothing; they get the victim’s browser to make an authenticated request by exploiting the exact behavior that made cookies convenient — automatic attachment. A form auto-submitted from evil.com, or an img tag pointing at a state-changing GET, and the browser dutifully includes your session cookie. HttpOnly is irrelevant here; the cookie is attached, not read. Two defenses, and you want both: SameSite on the cookie to stop the cross-site request from carrying it at all, and a server-side check — a CSRF token or an Origin/Sec-Fetch-Site assertion — for the cases SameSite does not cover, like same-site subdomains you do not trust.</p><h3>SameSite, and why the default is Lax</h3><p>Use Lax for session cookies and reserve None for the genuine third-party case. Strict is tempting and usually wrong: it drops the cookie even on a top-level navigation from an external link, so a user clicking your link in an email lands logged out, and support tickets follow. Lax sends the cookie on top-level GET navigations but not on cross-site POSTs, subresource loads, or iframes, which is exactly the shape of the classic CSRF form-submit — blocked — while the shape of a normal inbound link keeps working. None re-enables full cross-site sending but the browser rejects it now unless it is paired with Secure. That pairing requirement is what broke a wave of embedded widgets when Chrome flipped the unspecified default from None to Lax around 2020: integrations that had never set SameSite at all, and quietly relied on the old send-everywhere behavior, stopped receiving their own cookies inside third-party iframes. The wrong lesson people took was “add SameSite=None to fix it.” The right lesson was that an embed depending on third-party cookies was already living on borrowed time, because the deprecation of third-party cookies was coming for that pattern regardless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZ46n98QKN6VYemmZXzWXg.jpeg" /><figcaption>Whether a cookie rides along on a cross-site request, broken down by SameSite value and request type.</figcaption></figure><p>Prefix your session cookie name with __Host-. The browser enforces the rules the prefix implies: Secure required, no Domain attribute, path of /, which pins the cookie to the exact host that set it. The payoff is the subdomain-attack case that most people never model. If any subdomain of your registrable domain can be taken over — a stale CNAME to a deprovisioned SaaS bucket, a marketing microsite on a shared host — that subdomain can normally set a Domain-scoped cookie that your main app will accept and send. A __Host- cookie cannot be overwritten that way, because it refuses the Domain attribute entirely. It costs you nothing except a name change, so on any origin where you do not personally control every subdomain, treat it as default-on.</p><h3>Where each thing actually goes</h3><p>Auth is the case with the least room for taste. The session credential goes in a __Host-, HttpOnly, Secure, SameSite=Lax cookie, and the SPA stops trying to read it. For remember-me, pair a short-lived session cookie with a longer-lived refresh token cookie, rotate the refresh token on every use, and store only its hash server-side so you can enumerate and revoke sessions — a stolen refresh token that gets used a second time surfaces as a rotation mismatch you can alarm on. Step-up auth still gates the sensitive actions, because a remembered device is a convenience claim, not an identity proof.</p><pre>// Setting a hardened session cookie (Express)<br>res.cookie(&quot;__Host-session&quot;, sessionId, {<br>  httpOnly: true,   // invisible to document.cookie -&gt; limits XSS blast radius<br>  secure: true,     // HTTPS only (required by the __Host- prefix)<br>  sameSite: &quot;lax&quot;,  // blocks the classic cross-site CSRF POST<br>  path: &quot;/&quot;,        // required by __Host-; Domain must be omitted<br>  maxAge: 1000 * 60 * 30, // 30 minutes<br>});</pre><p>For multi-step flows and carts, the server holds the truth keyed by the session cookie; the client copy is a cache you are allowed to lose. Split it by lifetime: localStorage for a cart you want to survive a refresh or a return visit, sessionStorage for in-progress form fields that should die with the tab so a shared machine does not leak a half-typed form to the next person. Payment card data is the one hard line — it never touches any client store, not even transiently, because the moment it lands in your JS heap or localStorage your PCI scope expands to that origin and every script on it. Send it straight to the processor’s tokenized iframe or redirect and keep the raw PAN out of your DOM entirely; that boundary is a compliance requirement, not a preference, and it is cheaper to honor than to descope later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4CwrsVXmxGRlPpSNX9-EQ.jpeg" /><figcaption>A typical secure login: the browser sends credentials, the server issues flagged cookies, and only non-sensitive flags land in localStorage.</figcaption></figure><p>Cross-tab coordination — log out here, log out everywhere — has a clean primitive, so reaching for a polling interval is a tell that someone missed it. Use BroadcastChannel for same-origin pub/sub; it is the direct fit. The storage event is the fallback for older targets, with one edge that trips people: it fires in other tabs, not the one that made the change, so the tab that triggered the logout will not hear its own event and has to act locally as well. Neither survives across origins, and neither is a message queue — a tab that was closed during the broadcast simply misses it and reconciles from the server on next load, which is the behavior you want anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nh34CFKocy0PP4ZroPVGpA.jpeg" /><figcaption>One tab logs out and the rest follow, using the storage event or BroadcastChannel instead of polling.</figcaption></figure><h3>The third-party cookie is going away</h3><p>If your product embeds in someone else’s page, or embeds someone else’s, the cookie you rely on today may not arrive tomorrow. Chrome’s third-party cookie deprecation — repeatedly delayed, but directionally certain — kills the pattern where an embedded widget in a cross-site iframe reads its own cookies. Two replacements matter. CHIPS (Cookies Having Independent Partitioned State) lets an embed opt into a cookie that is partitioned by the top-level site, so state persists but is siloed per embedding site rather than shared across all of them. Privacy Sandbox replaces the measurement and interest-signal use cases that ad and analytics code was abusing cookies for. If you ship an embeddable SDK, assume the shared-cookie path is gone and design for partitioned or first-party-proxied state now, because retrofitting it after your integrators’ embeds silently stop working is the worst time to find out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43376760746" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>