Skip to content

Interview PrepCookies & sessions · Basics

Cookies ​

1. What are cookies, and what are they commonly used for? ​

The short answer

A cookie is a small piece of text, a name and a value, that a server asks the browser to store with the Set-Cookie response header. The browser then sends it back automatically, in a Cookie header, on every later request to that site. HTTP itself forgets everything between requests, so cookies are how a site remembers you. They are used for three things: sessions, such as keeping you logged in or holding a cart; preferences, such as language or theme; and tracking, such as analytics and advertising.

Why cookies were needed. HTTP is stateless. The server treats every request as if it came from a stranger. Without some memory on the client side, you would have to log in again on every click. A cookie is a ticket the server hands you once. You show it on every visit, and the server recognises you.

What a cookie looks like on the wire:

http
HTTP/1.1 200 OK
Set-Cookie: session=3f9a7c21; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400
http
GET /account HTTP/1.1
Host: shop.example
Cookie: session=3f9a7c21; theme=dark

The server sets session once. From then on, the browser adds it to every request for shop.example, with no JavaScript involved.

UseExample cookieWho sets it
Sessionsession=3f9a7c21Your server, after login
Preferencelang=en-GBYour server or your front end
Analytics_ga=GA1.2.…An analytics script
AdvertisingAn ad network's user IDA third-party ad domain

The limits: about 4 KB per cookie, and every cookie for a site is sent on every request to it, images and API calls included. Large or many cookies slow every request. Keep cookies small and put real data on the server.

2. What is the cookie lifecycle from server response to browser request? ​

The short answer

The server sends Set-Cookie in a response. The browser checks the attributes, rejecting the cookie if, say, it is Secure on a plain-HTTP page or names a domain the page does not belong to, and then stores it in its cookie jar. On each later request, the browser picks every stored cookie whose domain, path, Secure and SameSite rules match that request, and sends them in one Cookie header. The cookie lives until its Max-Age or Expires passes, the browser session ends for a session cookie, the server overwrites or deletes it, or the user clears it.

browser③ cookie jarsession=3f9ashop.example① POST /login② Set-Cookie: session=3f9a; HttpOnly; Secure; Max-Age=86400④ GET /account · Cookie: session=3f9a⑤ expires, or server sends Max-Age=0
Set once, sent automatically. ① The user logs in. ② The server hands over a cookie with its rules. ③ The browser checks the rules and stores it. ④ On every matching request, it attaches the cookie by itself. ⑤ The cookie ends when it expires or the server replaces it with an expired one.

How a server deletes a cookie. There is no delete command. The server sends the same cookie name, with the same Domain and Path, and Max-Age=0 or an Expires date in the past. If the Path or Domain differs, the browser treats it as a different cookie, and the old one survives. This is the most common reason "logout does not clear the cookie".

ts
res.clearCookie('session', { path: '/', httpOnly: true, secure: true, sameSite: 'lax' })   // same attributes as when it was set

3. What cookie metadata and attributes should developers understand? ​

The short answer

Beyond the name and value, a cookie carries rules the browser enforces. Domain and Path decide which URLs get it. Max-Age or Expires decide how long it lives. Secure sends it only over HTTPS. HttpOnly hides it from JavaScript. SameSite decides whether it is sent on requests started by other sites. Partitioned keeps a third-party cookie separate per top-level site. The name prefixes __Host- and __Secure- make the browser enforce safe settings.

AttributeControlsSafe default for a session cookie
DomainWhich hosts receive itLeave it out: this host only
PathWhich paths receive it/
Max-Age / ExpiresLifetimeShort, or leave out for a session cookie
SecureHTTPS onlyAlways
HttpOnlyHidden from JavaScriptAlways for auth cookies
SameSiteSent on cross-site requests?Lax or Strict
PartitionedSeparate jar per top-level siteOnly for embedded third-party use

Cookie name prefixes, a cheap extra lock:

PrefixBrowser accepts the cookie only if
__Secure-It has Secure and was set over HTTPS
__Host-It has Secure, Path=/, and no Domain
ts
res.cookie('__Host-session', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  path: '/',
  maxAge: 8 * 60 * 60 * 1000,                                                  // 8 hours, in milliseconds in Express
})

__Host- means the cookie is locked to this exact host. A compromised subdomain such as blog.shop.example cannot overwrite it, because it may not set a Domain.

Browsers cap lifetimes. Chrome limits Max-Age and Expires to 400 days. Safari can delete cookies set by JavaScript after 7 days without a visit. "Remember me for 5 years" is not possible.

4. What is the difference between a session cookie and a persistent cookie? ​

The short answer

A session cookie has no Max-Age or Expires. The browser keeps it only until the browsing session ends. A persistent cookie has a lifetime, and survives restarts until that time passes. Note that "session cookie" here means the lifetime, not "the cookie that holds a login session"; a login cookie can be either. Also, modern browsers often restore session cookies when they reopen tabs, so a session cookie may live far longer than you expect.

Session cookiePersistent cookie
Has Max-Age or ExpiresNoYes
Survives closing the browserUsually not, unless tabs are restoredYes
Typical useLogin without "remember me""Remember me", preferences

Do not rely on the browser to end a login. The cookie lifetime is only a hint the user's browser follows. The server must also expire the session on its side, with an idle timeout and an absolute timeout (how to secure cookie-based login).

5. What do the Domain and Path cookie attributes control? ​

The short answer

They decide which requests carry the cookie. Without Domain, the cookie is sent only to the exact host that set it. With Domain=shop.example, it is sent to shop.example and every subdomain, such as api.shop.example and blog.shop.example. Path=/account sends it only for URLs under /account. A site can only set Domain to itself or a parent it belongs to, never to a different site or a public suffix like .com. Path is a convenience, not a security boundary.

Set by app.shop.example withSent to app.shop.exampleapi.shop.exampleevil.example
No DomainYesNoNo
Domain=shop.exampleYesYesNo
Domain=evil.exampleRejected by the browser

Leaving Domain out is safer. Setting Domain=shop.example sends your session cookie to every subdomain, including a marketing site run by a vendor. If that subdomain is compromised, it receives every user's session.

Why Path is not security. A page at /blog on the same origin can open an iframe to /account and read its cookies through the frame's document. Same-origin pages can reach each other, so Path only reduces which requests carry the cookie.

6. What are Max-Age and Expires, and how do they differ? ​

The short answer

Both set when a persistent cookie stops being valid. Expires is a fixed date and time, such as Expires=Wed, 28 Oct 2026 10:00:00 GMT. It depends on the user's clock being right. Max-Age is a number of seconds from now, such as Max-Age=3600 for an hour, so it is not affected by a wrong clock. If both are present, Max-Age wins. Max-Age=0 deletes the cookie immediately. Without either, the cookie is a session cookie.

http
Set-Cookie: theme=dark; Max-Age=2592000                         # 30 days from now
Set-Cookie: theme=dark; Expires=Wed, 25 Nov 2026 10:00:00 GMT   # a fixed moment
Set-Cookie: theme=; Max-Age=0                                   # delete it now

An Express gotcha. res.cookie(name, value, { maxAge }) takes milliseconds, and Express converts that into both a Max-Age in seconds and an Expires date. Passing maxAge: 3600 gives a cookie that lives 3.6 seconds.

7. What does the HttpOnly attribute do? ​

The short answer

HttpOnly makes a cookie invisible to JavaScript: document.cookie does not show it, and scripts cannot read or change it. The browser still sends it on requests. This means that if an attacker manages to run script on your page through XSS, they cannot simply read the session cookie and send it to themselves. It does not stop XSS itself, since the injected script can still make requests from the victim's browser, but it stops the session from being stolen and reused elsewhere. Every authentication cookie should be HttpOnly.

ts
// with HttpOnly on the session cookie, on the page:
document.cookie   // 'theme=dark'   the session cookie is not listed

What HttpOnly protects, and what it does not:

An XSS attacker canWithout HttpOnlyWith HttpOnly
Copy the session to their own machineYesNo
Use the session later, after the victim closes the tabYesNo
Make requests as the victim while the page is openYesYes

So HttpOnly turns a permanent account takeover into a smaller attack that only lasts while the victim's tab is open. You still need to prevent XSS (the XSS question).

8. What does the Secure cookie attribute do? ​

The short answer

Secure tells the browser to send the cookie only over HTTPS, never over plain HTTP. Without it, a single http:// request, for example from an old link or a typed address before the redirect to HTTPS, would carry the session cookie unencrypted, where anyone on the same network can read it. Browsers also refuse to let a plain-HTTP page set a Secure cookie. SameSite=None cookies must be Secure. Use it on every cookie in production.

Local development is the exception. Browsers treat http://localhost as a secure context, so Secure cookies work there in Chrome and Firefox. Behind a proxy that ends TLS, Express only sets Secure cookies when it knows the original request was HTTPS, which needs trust proxy (the trust proxy question).

9. What is the SameSite attribute? ​

The short answer

SameSite tells the browser whether to send a cookie on requests that another site started. A "site" here is the scheme plus the registrable domain, such as https://shop.example, so api.shop.example is the same site. With SameSite=Strict or Lax, a form on evil.example that posts to your site arrives without your session cookie, which blocks most CSRF attacks. Browsers treat a cookie with no SameSite as Lax by default. Cookies that must work across sites, such as for embedded widgets, need SameSite=None; Secure.

Why this matters. Before SameSite, the browser attached your cookies to every request to your site, whoever started it. That is exactly what CSRF abuses (the CSRF question). SameSite lets the browser ask, "did this request come from the same site?" before attaching the cookie.

Same site versus same origin:

FromToSame origin?Same site?
https://shop.examplehttps://api.shop.exampleNoYes
https://shop.examplehttp://shop.exampleNoNo: scheme differs
https://shop.examplehttps://shop-pay.exampleNoNo

10. What are the differences between SameSite Strict, Lax, and None? ​

The short answer

Strict: the cookie is never sent on a request started by another site, not even when the user clicks a normal link to you. Lax: the cookie is sent when the user follows a top-level link with a safe method like GET, but not on cross-site POSTs, iframes, images or fetch calls. This is the default today. None: always sent, cross-site included, and it must also be Secure. Use Lax for most session cookies, Strict for very sensitive actions, and None only for cookies that truly must work inside other sites.

StrictLaxNonerequest started by another siteuser clicks a link to shop.exampletop-level GEThidden form POSTs to shop.examplethe CSRF caseiframe, image or fetch to shop.exampleembedded or backgroundnot sentsentsentnot sentnot sentsentnot sentnot sentsent
Who started the request decides. Every row is a request to shop.example that another site started. Requests your own pages make always carry the cookie. Lax allows only the top row, a normal link click, which keeps users logged in when they arrive from a search result while blocking the hidden form post.

Why Strict can annoy users. A user clicks a link to your site from an email. With Strict, the first page load arrives without the session cookie, so they look logged out until they click again. A common pattern is two cookies: a Lax one to show the logged-in page, and a Strict one required for sensitive actions like changing the password.

The default for cookies without SameSite. Chrome treats them as Lax. For two minutes after such a cookie is set, Chrome also allows it on top-level cross-site POSTs, so that older login flows keep working. Do not rely on the default; set the attribute explicitly.

Lax is not complete CSRF protection. A state-changing GET, like /logout?next=… or /transfer?to=…, is still exposed, because Lax allows top-level GETs. Never change data on GET.

11. What is the difference between first-party and third-party cookies? ​

The short answer

It depends on what is in the address bar. A first-party cookie belongs to the site the user is visiting: on shop.example, cookies for shop.example are first-party. A third-party cookie belongs to a different site whose content is embedded in the page, such as an ad, a social "like" button or an analytics script loaded from tracker.example. The same cookie for tracker.example is first-party when you visit tracker.example itself, and third-party when it is loaded inside shop.example.

On shop.exampleCookie forKind
Your loginshop.exampleFirst-party
Embedded video from video.examplevideo.exampleThird-party
Ad from ads.exampleads.exampleThird-party
Your own API at api.shop.exampleshop.exampleFirst-party, same site

Third-party cookies have legitimate uses too: an embedded chat or payment widget that keeps you signed in, and some older single sign-on designs that check a login in a hidden iframe. These are the cases that break when browsers block them.

12. Why have browsers restricted third-party cookies? ​

The short answer

Because their main use was tracking people across the web without their knowledge. One ad network embedded on thousands of sites sees its own cookie on each one, and so builds a history of everything you browse. Safari and Firefox now block or partition third-party cookies by default. Chrome planned to remove them, but in 2025 decided to keep them and leave the choice to users, and retired its Privacy Sandbox replacements. For developers this means: never design a login or important feature that depends on third-party cookies.

BrowserThird-party cookies by default
SafariBlocked
FirefoxPartitioned: each top-level site gets a separate jar
ChromeStill allowed; users can block them

Partitioned cookies, the replacement for legitimate uses. A cookie set with the Partitioned attribute, known as CHIPS, is stored separately for each top-level site. An embedded support-chat widget on shop.example gets one jar, and the same widget on news.example gets another. The widget still works on each site, but it cannot link your visits across them.

http
Set-Cookie: __Host-chat=abc; Secure; Path=/; SameSite=None; Partitioned

What to do instead of third-party cookies for login: use redirects with OpenID Connect (the OIDC login flow), keep the front end and API on the same site, and avoid hidden-iframe session checks.

13. What is cross-site tracking? ​

The short answer

Cross-site tracking is following one person's activity across many unrelated websites and linking it into one profile. Third-party cookies were the classic method: the same tracker on many sites reads the same ID. Other methods include fingerprinting, which identifies a browser from details like screen size, fonts and graphics card; link decoration, which adds IDs to URLs such as ?fbclid=…; and bounce tracking, which sends you through the tracker's site for a moment. Browsers fight each one, and privacy laws such as GDPR require consent for most tracking.

shop.examplenews.examplehealth-forum.exampletracker.examplecookie id=u42profile u42bought running shoesreads sports newsasked about knee pain
One ID, many sites. Each site embeds the same tracker. The tracker's third-party cookie is the same on all of them, so three unrelated visits join into one profile. Partitioned cookies break this link, because the tracker gets a different jar on each site.

What this means for you as a developer: load as few third-party scripts as you can, get consent before setting tracking cookies, and prefer first-party, server-side analytics. Each third-party script is also a security risk, because it runs with full access to your page.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Authentication & Identity
Cookies & sessions
Authentication
Tokens
OAuth & OIDC
Enterprise SSO
Directories
Authorization
Other topics
Nothing picked yet