Q012: Cookies, Sessions, SameSite, HttpOnly and Secure
What Interviewers Want To Evaluate
This question tests whether you understand browser authentication mechanics and cookie security. Interviewers want to know how cookies work, why sessions use cookies, what HttpOnly, Secure, and SameSite do, and how cookie choices relate to XSS, CSRF, cross-site requests, subdomains, and modern browser privacy restrictions.
For senior roles, the interviewer is looking for security judgment. You should be able to explain not only flags, but also why a team would choose cookie-based sessions, token storage, refresh flows, or backend-for-frontend patterns.
Short Interview Answer
Cookies are small pieces of state stored by the browser and automatically attached to matching HTTP requests. They are commonly used to carry a session identifier so the server can look up authenticated user state. HttpOnly prevents JavaScript from reading the cookie, which reduces token theft risk from XSS. Secure ensures the cookie is sent only over HTTPS. SameSite controls when cookies are sent on cross-site requests and helps reduce CSRF. Cookie design must consider domain, path, expiration, request overhead, CSRF, XSS, logout, and subdomain scope.
Detailed Interview Answer
When a server sends a Set-Cookie header, the browser stores the cookie if policy allows it. On later requests, the browser attaches matching cookies based on domain, path, scheme, expiration, and same-site rules. This automatic attachment is what makes cookies convenient for sessions.
In a session-based auth model, the cookie usually stores an opaque session ID, not the whole user record. The server uses that ID to look up session state. This allows server-side revocation and smaller client exposure. In token-based systems, a cookie might store a refresh token or session token, depending on the architecture.
The security flags matter. HttpOnly makes the cookie unavailable to document.cookie. Secure requires HTTPS. SameSite=Lax or Strict reduces cross-site request risk. SameSite=None allows cross-site usage but requires Secure and should be used carefully.
Deep Technical Explanation
Cookie behavior is controlled by request matching and attributes.
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
Browser stores cookie
-> future matching request
-> browser attaches Cookie header
-> server validates session
The cookie is not manually added by frontend JavaScript in normal browser navigation. The browser attaches it according to cookie rules.
Internal Working
Cookies have attributes:
Domaincontrols which hostnames receive the cookie.Pathcontrols which URL paths receive the cookie.ExpiresorMax-Agecontrols persistence.HttpOnlyblocks JavaScript reads.Securerestricts transmission to HTTPS.SameSitecontrols cross-site sending behavior.
Host-only cookies are often safer than broad domain cookies because they reduce subdomain exposure.
Architecture Discussion
Cookie-based sessions are common for web applications because they integrate naturally with browser requests and server rendering. They also allow session revocation on the server. However, because cookies are automatically sent, teams must think about CSRF.
Token-in-localStorage designs avoid automatic cookie sending but increase exposure to XSS. Token-in-cookie designs reduce JavaScript access but need CSRF protection and proper SameSite settings. Backend-for-frontend architectures often use HttpOnly cookies between browser and BFF, while the BFF handles downstream tokens.
Trade-Offs
HttpOnly improves protection from token theft but means JavaScript cannot read the token. SameSite=Strict is safer but can break cross-site login flows. SameSite=Lax is a practical default for many apps. SameSite=None supports cross-site embedding or federated flows but expands risk and requires Secure.
Short-lived sessions reduce risk but can hurt user experience. Long-lived sessions improve convenience but require revocation, rotation, and anomaly detection.
Common Mistakes
A common mistake is saying HttpOnly prevents XSS. It does not. It only prevents JavaScript from reading that cookie. XSS can still perform actions as the user if the page is compromised.
Another mistake is ignoring CSRF because the app uses cookies. Automatic cookie sending is exactly why CSRF must be considered.
Real Production Story
A web app may use SameSite=None for an embedded flow and accidentally send cookies in more cross-site contexts than intended. Later, a CSRF-like issue appears because state-changing endpoints rely only on cookie authentication.
The fix may include SameSite=Lax where possible, CSRF tokens for state-changing operations, origin checks, stricter CORS, and separating embedded flows onto narrower cookies.
Enterprise Example
In an enterprise SaaS app with SSO, the app may need redirects across identity providers, custom domains, and subdomains. Cookie configuration becomes architecture. The team must decide host-only versus domain cookies, session duration, refresh behavior, logout propagation, and whether third-party cookie restrictions affect embedded customer portals.
Code Example
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600
This cookie is not readable by JavaScript, is sent only over HTTPS, is scoped to the site path, and uses a SameSite mode that reduces many CSRF risks while still allowing some top-level navigations.
// Client code can check authentication state through an endpoint,
// without reading the session cookie directly.
export async function fetchCurrentUser() {
const response = await fetch("/api/me", {
credentials: "include",
});
if (!response.ok) {
return null;
}
return response.json();
}
The browser sends eligible cookies with the request. The frontend does not need to read the session cookie.
Performance Discussion
Cookies are sent on matching HTTP requests, so large cookies add request overhead. This is especially wasteful for static asset requests if domain/path scoping is too broad. Keep cookies small, scoped, and purposeful.
Security Considerations
Cookie security is mostly about reducing exposure and unintended sending. Use HTTPS, Secure, HttpOnly for session cookies, appropriate SameSite, short lifetimes for sensitive sessions, server-side invalidation, CSRF protection where needed, and careful domain scoping.
Also consider session fixation, token rotation, logout cleanup, and whether subdomains are equally trusted.
Scalability Discussion
Server-side sessions require shared session storage or sticky routing unless the architecture avoids it. Stateless signed tokens reduce lookup needs but complicate revocation. At scale, session architecture must balance revocation, latency, storage, observability, and security.
Senior Engineer Perspective
A senior engineer should explain cookies through browser behavior and threat models. The best answer says what each flag does, what it does not do, and how cookie choices affect authentication architecture.
Lead Engineer Perspective
A lead engineer should define auth cookie standards, CSRF rules, CORS policy, session rotation, logout behavior, monitoring, and review checklists for new state-changing endpoints.
Whiteboard Explanation
Draw login returning Set-Cookie, the browser storing it, future requests attaching it automatically, and the server resolving the session. Then annotate HttpOnly, Secure, and SameSite at the browser boundary.
Revision Notes
Cookies are automatically sent with matching requests. HttpOnly blocks JavaScript reads. Secure requires HTTPS. SameSite controls cross-site sending. Cookies are useful for sessions but require CSRF and scoping discipline.
Key Takeaways
Cookie security is not one flag. It is a combination of browser rules, server validation, session design, CSRF strategy, and careful scoping.
Related Topics
- Browser storage
- XSS
- CSRF
- CORS
- Authentication
- Session management
- Same-origin policy
- Backend-for-frontend architecture
Practice Exercise
Inspect cookies on a site you use frequently. Identify which cookies are HttpOnly, Secure, persistent, host-only, or SameSite configured. Explain which ones appear security-sensitive.
Follow-Up Questions
- What is a cookie?
- What does
HttpOnlyprotect against? - What does
Securedo? - What is
SameSite=Lax? - When is
SameSite=Nonerequired? - Why can cookies create CSRF risk?
- Why are large cookies bad?
- What is the difference between host-only and domain cookies?
- How do sessions differ from JWTs?
- How would you design logout cleanup?
Things Interviewers Hate Hearing
"HttpOnly makes cookies secure" is too broad. It prevents JavaScript reads, but it does not stop XSS from acting as the user or remove the need for CSRF protection.
How I Would Answer This In A Real Interview
I would say cookies are browser-managed state that are automatically sent with matching HTTP requests. For sessions, the cookie often stores an opaque session ID, and the server resolves that ID to user state. HttpOnly prevents JavaScript from reading the cookie, Secure restricts it to HTTPS, and SameSite controls cross-site sending to reduce CSRF risk.
Then I would discuss design trade-offs. Cookie sessions are good for server-rendered web apps and revocation, but they need CSRF strategy and careful domain scoping. Storing tokens in JavaScript-accessible storage can avoid automatic cookie sending, but it increases XSS theft risk. I would choose based on threat model, app architecture, SSO needs, and operational requirements.