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.
More medium Frontend Developer questions
- Explain the JavaScript event loop, including microtasks and macrotasks.
- How do you decide where to keep state in a React app: local state, context, a store, or a server-cache library?
- A page has a poor LCP score. How would you investigate and fix it?
- What testing strategy would you use for a frontend application?
- Explain client-side rendering, server-side rendering and static site generation. When would you use each?
- What happens between typing a URL in the browser and seeing the page rendered? Focus on the frontend side.
- A React screen feels slow. How do you find and reduce unnecessary re-renders?
- How do you handle loading, error and empty states when a screen fetches data from an API?
- How do you use TypeScript effectively in a React codebase?