Skip to content

Interview PrepCookies & sessions · Core

Sessions ​

14. What is session hijacking, and how can it be prevented? ​

The short answer

Session hijacking is when an attacker gets hold of a valid session ID and uses it to act as the user, with no password needed. They steal it through XSS reading the cookie, sniffing unencrypted traffic, malware on the device, leaked logs or URLs, or session fixation, where they plant a known session ID on the victim before login. Prevent it with HttpOnly, Secure and SameSite cookies, HTTPS everywhere, long random session IDs, a new session ID at login, idle and absolute timeouts, server-side logout, and re-asking for the password before sensitive actions.

Session fixation, the attack that "new ID at login" stops:

  1. The attacker visits your site and gets an anonymous session ID, abc.
  2. They trick the victim into using abc, for example through a link on a site that accepts session IDs in the URL, or a cookie set from a compromised subdomain.
  3. The victim logs in. If your server keeps the same ID and marks it logged in, the attacker's copy of abc is now logged in too.

The fix is to issue a brand-new session ID the moment the user logs in, and throw the old one away.

ts
app.post('/login', async (req, res, next) => {
  const user = await verifyCredentials(req.body.email, req.body.password)
  req.session.regenerate((err) => {                                              // (1)
    if (err) return next(err)
    req.session.userId = user.id                                                 // (2)
    req.session.authAt = Date.now()                                              // (3)
    res.json({ ok: true })
  })
})
  1. Destroy the old session and create a new one with a fresh ID. Any ID the attacker planted is now worthless.
  2. Store only the user's ID in the session, not the whole user record.
  3. Remember when they authenticated, so sensitive actions can demand a fresh login after, say, 15 minutes.
Way a session is stolenPrevention
XSS reads document.cookieHttpOnly, plus CSP (the CSP question)
Sniffed on public Wi-FiHTTPS everywhere, Secure, HSTS
Session fixationNew session ID at login
ID in a URL or logIDs only in cookies; never log them
GuessingAt least 128 bits of randomness
Stolen laptop or malwareShort idle timeout, "log out everywhere", device-bound sessions

Detecting a stolen session. Some apps record the device and rough location at login, and ask for the password again if the same session suddenly appears from another country. This is a signal, not proof, because phones change networks all the time.

15. How does SameSite help protect against CSRF? ​

The short answer

CSRF works because the browser attaches your session cookie to a request even when another site started it. With SameSite=Lax or Strict, the browser leaves the cookie off cross-site POSTs, iframes and background requests. So the attacker's hidden form reaches your server without a session, and the action fails as if the user were logged out. Lax still sends the cookie on top-level GET navigations, so data must never change on GET. For strong protection, combine SameSite with a CSRF token or an Origin header check.

Where SameSite alone leaves gaps:

GapWhyFix
State change on GETLax sends cookies on top-level GETOnly POST, PUT, DELETE change data
Attack from your own subdomainSame site, so SameSite does not applyCSRF token; keep subdomains trustworthy
SameSite=None cookiesSent everywhere by designCSRF token required
Very old browsersIgnore the attributeCSRF token

A cheap extra check: for every state-changing request, compare the Origin header with your own origin. Browsers set Origin on cross-site POSTs, and pages cannot fake it. The full CSRF picture, with the double-submit token, is in the CSRF question.

16. How should cookie-based authentication be secured? ​

The short answer

Use a long random session ID as the only thing in the cookie, with all real data on the server. Set the cookie HttpOnly, Secure, SameSite=Lax, Path=/, no Domain, ideally named __Host-session. Issue a new ID at login. Expire the session after a period of no activity and after a fixed maximum, both on the server. Delete it on the server at logout. Add CSRF protection for state-changing requests. Re-ask for the password before sensitive actions. Offer "log out of all devices".

ts
import session from 'express-session'

app.set('trust proxy', 1)

app.use(session({
  name: '__Host-session',                                                        // (1)
  secret: [config.SESSION_SECRET, config.SESSION_SECRET_PREVIOUS],               // (2)
  store: redisStore,                                                             // (3)
  resave: false,
  saveUninitialized: false,                                                      // (4)
  rolling: true,                                                                 // (5)
  cookie: { httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 30 * 60 * 1000 },
}))

app.use((req, res, next) => {
  const MAX_AGE = 12 * 60 * 60 * 1000
  if (req.session.authAt && Date.now() - req.session.authAt > MAX_AGE) {         // (6)
    return req.session.destroy(() => res.status(401).json({ error: 'Session expired' }))
  }
  next()
})
  1. The __Host- prefix makes the browser refuse the cookie unless it is Secure, has Path=/ and no Domain.
  2. An array of secrets lets you rotate the signing secret. The first one signs new cookies, and all of them are accepted.
  3. A shared server-side store, such as Redis, so sessions survive restarts and work across instances (question 19).
  4. Do not create sessions for anonymous visitors, which saves storage and stops bots from filling it.
  5. Idle timeout: each request pushes the 30-minute expiry forward, so an unused session dies after 30 minutes.
  6. Absolute timeout: even an active session ends 12 hours after login.

Logout must delete the server-side session, not just the cookie:

ts
app.post('/logout', (req, res, next) => {
  req.session.destroy((err) => {
    if (err) return next(err)
    res.clearCookie('__Host-session', { path: '/', httpOnly: true, secure: true, sameSite: 'lax' })
    res.status(204).end()
  })
})

How long sessions should last. It depends on risk. A banking app may use a 5 to 15 minute idle timeout. A shopping site might keep users signed in for weeks, but ask for the password again before changing the email address or viewing saved cards.

17. What is express-session, and how does it work? ​

The short answer

express-session is middleware that gives each visitor a server-side session object, req.session. On the first request where you put something in it, it creates a random session ID, saves the data in a store keyed by that ID, and sends the ID to the browser in a signed cookie, by default named connect.sid. On every later request, it reads the cookie, checks the signature, loads the data from the store into req.session, and saves any changes at the end of the request. Its default store is in memory and is not for production.

browserconnect.sid=s:k3j9.Xb2…express-session② check signaturewith the secret⑤ save changeswhen the response endsroutereq.session.cartstore, e.g. Redissess:k3j9 → {userId: 42, …}①③ load④
The cookie is only a claim ticket. ① The browser sends the signed ID. ② The signature proves the ID was issued by this server. ③ The real data is loaded from the store. ④ Your route uses req.session like a normal object. ⑤ Changes are written back when the response finishes.

What is in the cookie. s: followed by the session ID, a dot, and an HMAC signature of that ID made with your secret. The signature stops a user from editing the ID to guess other sessions. The data itself is never in the cookie.

The options people get asked about:

OptionMeaningUsual value
secretSigns the cookieLong random, from a vault; an array to rotate
storeWhere session data livesRedis, a database; never the default in production
resaveSave even if unchangedfalse
saveUninitializedSave brand-new empty sessionsfalse
rollingReset the expiry on every responsetrue for an idle timeout
cookieCookie attributeshttpOnly, secure, sameSite, maxAge

Why the memory store is not for production: it leaks memory, every restart logs everyone out, and with several instances each one has different sessions, so users appear logged out at random.

Typing req.session in TypeScript:

ts
declare module 'express-session' {
  interface SessionData { userId: string; authAt: number; cart: string[] }
}

18. How do stateful and stateless sessions differ? ​

The short answer

In a stateful session, the server keeps the session data, and the client holds only a random ID that points to it, as with express-session and Redis. In a stateless session, the client holds all the data itself, in a signed token such as a JWT or a signed cookie, and the server keeps nothing; it just checks the signature. Stateful is easy to revoke and keeps data private, but needs a shared store. Stateless needs no lookup, but cannot be cancelled before it expires unless you add back some server-side state.

StatefulStateless
Client holdsRandom IDAll claims, signed
Server holdsSession dataOnly the signing key
Each requestStore lookupSignature check
Log out immediatelyDelete the recordHard: wait for expiry or keep a block list
Change a user's role nowUpdate the recordOld tokens keep the old role until they expire
Size on the wireSmallLarger, every request
ScalingShared store neededAny instance can check

The honest summary for an interview. Stateless sounds simpler, but most real systems need "log this user out now" and "this user was just banned". The moment you add a revocation list, you have a lookup again. That is why many web apps use stateful sessions for browsers, and keep short-lived stateless tokens for service-to-service calls (the revocation question).

19. How do distributed sessions work across multiple application instances? ​

The short answer

When a load balancer spreads requests across many app instances, any instance must be able to find any user's session. There are three ways. A shared store: all instances read and write sessions in Redis or a database. This is the standard answer. Sticky sessions: the load balancer always sends a user to the same instance, which is simple but breaks when that instance restarts or is removed. Stateless tokens: put the session in a signed cookie or JWT so no store is needed, with the revocation trade-offs.

usersid=k3j9load balancerinstance Arequest 1instance Brequest 2Redissess:k3j9
Any instance, same session. The user's two requests land on different instances. Both load the session from the same Redis key, so the user never notices which machine answered. Restarting or adding instances logs nobody out.
ts
import session from 'express-session'
import { RedisStore } from 'connect-redis'
import { createClient } from 'redis'

const redis = createClient({ url: config.REDIS_URL })
await redis.connect()

app.use(session({
  store: new RedisStore({ client: redis, prefix: 'sess:' }),                     // (1)
  secret: config.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 30 * 60 * 1000 },
}))
  1. Every instance uses the same Redis, so a session written by instance A is read by instance B. The store sets a Redis expiry on each key equal to the cookie's lifetime, so old sessions delete themselves.
ApproachGoodBad
Shared Redis storeAny instance works; instant logoutRedis must be highly available
Sticky sessionsNo extra infrastructureLost on restart; uneven load
Signed-cookie or JWT sessionsNo storeHard to revoke; cookie size limit

If Redis goes down, every user looks logged out. Run Redis with a replica and automatic failover, and alert on it like any database.

20. What is the difference between cookie-based authentication and JWT-based authentication? ​

The short answer

The question mixes two separate choices: where the credential is stored and sent, a cookie or an Authorization header, and what the credential is, a random session ID or a self-contained JWT. Classic "cookie auth" means a session ID in an HttpOnly cookie, looked up on the server. Classic "JWT auth" means a signed token kept by the client and sent as Authorization: Bearer …, checked without a lookup. Browsers favour cookies because JavaScript cannot steal them. Mobile apps and APIs favour bearer tokens. You can also put a JWT inside a cookie.

Session ID in a cookieJWT as a bearer token
Sent howBrowser adds the cookieYour code adds the header
Readable by JavaScriptNo, with HttpOnlyYes, so XSS can steal it
CSRF riskYes, needs SameSite or a tokenNo, browsers do not add headers by themselves
Server lookupYes, the storeNo, check the signature
Revoke nowDelete the sessionHard (the revocation question)
Works across domains and for mobileAwkwardEasy

The recommendation most interviewers want to hear. For a browser app talking to its own back end: an HttpOnly, Secure, SameSite session cookie. For a mobile app, a third-party API client or service-to-service calls: short-lived bearer tokens. For a browser app that needs tokens from an identity provider, keep the tokens on the server and give the browser only a session cookie. This is called the back end for front end pattern (the token storage question).

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