Skip to content
RED SAGSkills
mediumFrontend Developer interview question

How would you handle user authentication and tokens in a single-page app or Next.js frontend?

What the interviewer wants to hear

  • Prefer HttpOnly, Secure, SameSite cookies managed by the server over tokens in localStorage
  • Protect against CSRF with SameSite and CSRF tokens for state-changing requests
  • Short-lived access tokens with refresh handled server-side or by a backend-for-frontend
  • Protect routes on the server, not only by hiding UI on the client
  • Handle expiry gracefully: refresh, retry once, or redirect to login and keep the intended path

Model answer

My default is to let the server manage the session in an HttpOnly, Secure, SameSite cookie. JavaScript cannot read it, so an XSS bug cannot simply steal the token, which is the main weakness of storing tokens in localStorage. Because cookies are sent automatically, I add CSRF protection: SameSite=Lax or Strict, safe GET endpoints, and CSRF tokens for sensitive actions. When an external identity provider is involved, I use the authorization code flow with PKCE, ideally through a backend-for-frontend so access and refresh tokens never reach the browser. On the frontend I treat auth state as data from the server, not as truth: hiding a menu item is only UX, and real checks happen in the API and in server-side route protection, such as middleware or server components in Next.js. When a session expires, I try a silent refresh once, otherwise redirect to login and return the user to the page they wanted.

Can you answer it under time pressure?

Take a timed medium round and get scored on every answer.

Start mock interview

More medium Frontend Developer questions