- Home
- Interview Questions
- JavaScript
- How do HttpOnly, Secure and SameSite cookie flags protect ag…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: HttpOnly stops JavaScript from reading a cookie, which limits token theft through XSS. Secure ensures the cookie is sent only over HTTPS. SameSite controls whether the cookie is sent on cross-site requests, which is the main browser-level defence against CSRF.
Detailed explanation
Session cookies are attractive targets because the browser attaches them to requests automatically. Each flag addresses a different attack.
HttpOnly
A cookie marked HttpOnly does not appear in document.cookie, so injected script cannot read it and send it to an attacker. It does not stop XSS itself. Malicious script running on your page can still call fetch('/api/transfer'), and the browser will attach the cookie. HttpOnly prevents the token from being stolen, not from being used while the XSS is active.
Secure
The cookie is sent only over HTTPS, so it cannot leak on a plain HTTP connection where a network attacker could read it. Modern browsers treat http://localhost as a secure context for development.
SameSite
This flag decides whether the cookie goes along on requests that start from a different site. Here, site means scheme plus registrable domain, for example https://example.com. It is not the same as origin.
- Strict: never sent on cross-site requests, including when a user clicks a link from another site to yours. Safest, but users can appear logged out after arriving from an external link.
- Lax: sent on top-level navigations with safe methods such as GET link clicks. Not sent on cross-site POST forms, iframes, images or fetch calls. This blocks the classic auto-submitting form CSRF attack.
- None: sent in all contexts. Browsers require Secure with it. Needed for genuine cross-site use such as embedded widgets or third-party login flows.
Chromium-based browsers treat a cookie without a SameSite attribute as Lax. Other browsers may differ, so always set the attribute explicitly.
Limits to know
- Subdomains count as the same site. A compromised
blog.example.comcan send same-site requests toapp.example.com, so SameSite does not protect you there. - Lax still allows cross-site GET navigations. Any GET endpoint that changes state remains vulnerable. Keep GET requests free of side effects.
- For defence in depth, combine SameSite with CSRF tokens or Origin header checks on sensitive actions.
The __Host- name prefix adds further hardening. The browser accepts such a cookie only if it is Secure, has Path=/ and has no Domain attribute, so a subdomain cannot overwrite it.
Example
// Response header for a hardened session cookie
Set-Cookie: __Host-sid=a8f3c2...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
// Express example
app.post('/login', (req, res) => {
const sid = createSession(req.body.user);
res.cookie('__Host-sid', sid, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 1000
});
res.sendStatus(204);
});
// In the browser, the session cookie is not visible
console.log(document.cookie); // does not include __Host-sidScenario: an attacker's page contains a hidden form that POSTs to https://bank.example/transfer. With SameSite=Lax, the browser does not attach the session cookie to that cross-site POST, so the request arrives unauthenticated.
Common mistakes
- Claiming HttpOnly prevents XSS. It only prevents reading the cookie. The attacker can still act as the user while their script runs.
- Setting
SameSite=Nonewithout Secure. Modern browsers reject such a cookie. - Confusing site with origin, and assuming SameSite blocks requests from your own subdomains.
- Relying on Lax while performing state changes on GET routes such as
/logoutor/delete?id=5.
Follow-up questions
- Should a JWT be stored in localStorage or in an HttpOnly cookie, and what are the trade-offs?
- How does a synchronizer CSRF token or the double-submit cookie pattern work?
- Why do third-party login or embedded-iframe flows often need SameSite=None?
Interview tip: Map each flag to the threat it addresses (HttpOnly to token theft through XSS, Secure to network sniffing, SameSite to CSRF), then explain the limits of each. Covering the limits is what shows senior-level understanding.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More hard JavaScript questions
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · 1 ans
- Why is using await inside a loop often slow, and how do you run async tasks in parallel? · 1 ans
Related Questions
- What is the difference between localStorage, sessionStorage and cookies in the browser? · JavaScript · 1 ans
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · JavaScript · 1 ans
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- Why is using await inside a loop often slow, and how do you run async tasks in parallel? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)