tezvyn:

Session auth in Next.js with API routes and middleware

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Session flow on a hybrid framework.

OUTLINE

Login route sets a signed httpOnly cookie, middleware validates the session at the edge and redirects, server components read the session.

WHAT THIS TESTS Your grasp of authentication in a framework that mixes static rendering, serverless functions, and edge middleware, where you cannot rely on a single long-lived process holding session state.

A GOOD ANSWER COVERS The login API route or route handler verifies credentials, creates a session, and responds with a Set-Cookie that is httpOnly, Secure, and SameSite, holding either a session identifier backed by an external store like Redis or a database, or a signed stateless token. On subsequent requests, middleware runs at the edge before the matched route, reads and verifies the cookie, and redirects unauthenticated users to login or rewrites the response. Inside server components and route handlers you read the cookie per request via the cookies API to load the user. Logout clears the cookie and invalidates the server-side session if stored.

COMMON WRONG ANSWERS Storing sessions in a module-level variable, which does not survive across stateless invocations or multiple instances. Putting the token in localStorage and losing httpOnly protection. Doing auth checks only in client components, which can be bypassed. Forgetting that middleware runs on the edge runtime with limited APIs.

LIKELY FOLLOW-UPS Stateful session store versus stateless signed token trade-offs? Why can't middleware use Node-only APIs? How do you revoke a stateless token? How does this interact with server components versus client components?

ONE CONCRETE EXAMPLE A user posts to /api/login; the handler checks the password, writes a session row to Redis, and sets cookie sid=abc123 as httpOnly Secure SameSite=Lax. The user visits /dashboard; middleware intercepts, reads sid, looks it up, and either allows the request or redirects to /login. The dashboard server component reads the same cookie to fetch the profile. Unlike a monolithic Express app, no in-memory session map is trusted, because each serverless function is a fresh, short-lived instance.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.