Authentication and session lifecycle
Implement a signed cookie session without a session database, understand its security limits, and synchronize server identity with the hydrated client.
What you will be able to do
- Distinguish identity verification, session tracking and permissions.
- Describe secure cookie and token responsibilities.
- Read and expire sessions on the server.
- Prevent cross-user state reuse after login or logout.
- Implement a minimal jose-signed cookie lifecycle without storing sessions in a database.
- Explain JWS integrity versus JWE confidentiality and bearer-token sensitivity.
- Hydrate a client session view from a verified server snapshot and refresh it after login/logout.
Before this lesson
Identity is a server decision
Authentication answers who the caller is. A session lets subsequent requests carry evidence of that established identity. Authorization asks what that identity may do. Keeping these questions separate prevents an implementation from treating a React isLoggedIn boolean as permission to read a private record.
In a real application, use an established authentication library or identity provider appropriate to the product. The learning lab may use a deliberately bounded demonstration identity so no real account or credential is required. That is a teaching convenience, not a production login design. Before replacing it, define account recovery, session expiry, revocation and abuse controls as actual product requirements.
Persist a session without a session database
An opaque session stores a random identifier in the browser and resolves it against server-side state. A stateless cookie session stores a signed set of claims in the browser. The server verifies the signature and required claims on each request, so it does not need a session row merely to recognize that token. The user identity can originally come from an external identity provider or a trusted account system. Removing the session database does not remove the need to verify login credentials.
The token is session state, the signing key and verification policy are server state, and the browser has cookie state. Stateless describes the absence of a per-session lookup for the basic verification path. It does not mean the application has no state, no secrets or no operational dependencies. Every replica must have a consistent verification key policy or the same cookie will be accepted by some requests and rejected by others.
Choose the trade-off explicitly. Opaque sessions allow the server to revoke an individual session by changing its record, but require a reachable session store. A signed stateless session is convenient when short-lived claims and no per-session lookup fit the requirements, but individual immediate revocation requires added state or an external authority. Redis, a key-value store or a denylist is still state even if no relational database is used.
Signing protects integrity; encryption protects confidentiality
A common JWT has three Base64url-encoded parts and uses JWS to protect integrity with a digital signature or MAC. Encoding is not encryption. Anyone who possesses that signed token can generally decode its claims; changing a claim invalidates the signature, but reading it does not. The server must verify it with a pinned algorithm and expected issuer/audience, not merely decode JSON and trust the role field.
JWE encrypts a token's content and provides a different confidentiality property. That can hide claims from the holder, but does not make a stolen bearer credential harmless or solve revocation. Keep claims minimal even when encrypted. Do not include passwords, signing keys, provider secrets or unnecessary personal details. A user ID, issue time, expiry and intended audience may be sufficient for the narrow learning example.
The access or session token is not the server's signing secret, yet it is still a sensitive bearer credential: possession may grant access until expiry or revocation. A signed token with harmless-looking claims must not be posted publicly. Conversely, an asymmetric verifier's public key is designed to be shareable, while the private signing key is not. HS256 uses one shared secret for signing and verification, so every verifier holding it can also mint tokens.
Preserve intent without an open redirect
When a protected request sends a visitor to login, preserve a safe intended destination. A returnTo value from the URL is untrusted. Accept a local application path using a defined allowlist or a same-origin URL check, and reject protocol-relative URLs and unexpected schemes. Otherwise the application can authenticate the user and then send them to an attacker-controlled page.
After login, create or rotate the session and show confirmed identity from a server read. Keep login validation distinct from account existence details that could leak sensitive information. For the exercise, we validate a simplified session policy and local return path. It intentionally does not verify a real cryptographic token or replace an authentication provider.
Do not reuse one user's data for another
Session data belongs to the request. With Cache Components, session reads are request-specific and should be placed behind an appropriate boundary. If a verified user ID is used to cache that user's nonsecret data, include it in the cache identity and keep permission checks outside an unsafe shared result. Do not cache a global currentUser value across requests.
Client caches also need a lifecycle. After account change or logout, clear or partition data by identity and prevent a delayed response from the old session from repopulating the new screen. A redirect alone can leave old state in a persistent provider. Think through two tabs, browser back navigation and an expired session during form submission.
Define what ending a session means
Logout should remove the browser credential and invalidate the server session when the design supports revocation. Deleting a cookie from one tab does not magically recall a copied token elsewhere. A stateless token design needs an explicit expiry/revocation policy. Session rotation, permission changes and device-wide logout should be discussed from those constraints.
Test a fresh request after logout, not just the disappearance of the avatar. The protected endpoint must reject the old identity evidence according to the chosen contract. Also test expiry at the boundary time and clock assumptions. A useful interview answer traces the same identity through login, storage, request verification, renewal, revocation and UI cache cleanup.
Implement a minimal signed cookie lifecycle with jose
The following server-only module is a complete minimal session-signing, verification, cookie and logout layer for the explained contract. Install jose in the real Next.js project. Set SESSION_SECRET to a cryptographically generated random value with at least 256 bits of entropy and keep it in server configuration, never a NEXT_PUBLIC variable or source-controlled file. The length check below rejects short values but cannot prove entropy. Do not generate a different key on every process start.
Call createSession only after a trusted authentication step succeeds. That step is deliberately outside this session helper; passing an arbitrary browser-submitted userId would let anyone impersonate anyone. Cookie writes and deletion must run in a Server Action or Route Handler. readSession can be called during a server read, and protected actions must call it again rather than trusting a DTO returned earlier to the client.
The helper uses a 15-minute lifetime as an explicit teaching policy. jwtVerify checks the signature and claims; requiredClaims prevents an otherwise valid token with missing expiry from becoming indefinite. Invalid credentials return no session. Missing server configuration throws outside the verification catch so an operational misconfiguration is not silently mislabeled as an anonymous user. The helper intentionally has no individual revocation store.
Server execution
import "server-only";
import { SignJWT, jwtVerify } from "jose";
import { cookies } from "next/headers";
const issuer = "frontendx-interview-lab";
const audience = "frontendx-interview-browser";
const production = process.env.NODE_ENV === "production";
const cookieName = production ? "__Host-fx_session" : "fx_session";
const lifetimeSeconds = 15 * 60;
function signingKey() {
const secret = process.env.SESSION_SECRET;
if (!secret) throw new Error("Missing SESSION_SECRET");
const key = new TextEncoder().encode(secret);
if (key.byteLength < 32) throw new Error("SESSION_SECRET must contain at least 32 bytes");
return key;
}
export async function createSession(verifiedUserId: string) {
if (!verifiedUserId) throw new Error("Missing verified user identity");
const token = await new SignJWT({})
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
.setSubject(verifiedUserId)
.setIssuer(issuer)
.setAudience(audience)
.setIssuedAt()
.setExpirationTime("15m")
.sign(signingKey());
(await cookies()).set(cookieName, token, {
httpOnly: true,
secure: production,
sameSite: "lax",
path: "/",
maxAge: lifetimeSeconds,
});
}
export async function readSession() {
const token = (await cookies()).get(cookieName)?.value;
if (!token) return null;
const key = signingKey();
try {
const { payload } = await jwtVerify(token, key, {
algorithms: ["HS256"],
issuer,
audience,
typ: "JWT",
requiredClaims: ["sub", "iat", "exp"],
maxTokenAge: "15m",
});
if (typeof payload.sub !== "string" || !payload.sub || typeof payload.exp !== "number") return null;
return { userId: payload.sub, expiresAt: payload.exp };
} catch {
return null;
}
}
export async function deleteSession() {
(await cookies()).delete(cookieName);
}Follow the cookie into a stable hydrated snapshot
After the server sends Set-Cookie, the browser stores the cookie according to its attributes. On a matching same-origin navigation or fetch, the browser includes the cookie automatically; JavaScript does not need to read an HttpOnly token and should not receive the signing secret. On the server, await cookies(), verify the token and derive the minimum safe DTO. Render that DTO into the initial page and pass it to a Client Component provider.
The provider below reads the current session prop directly. Avoid useState(initialSession) when later server refreshes should replace that snapshot: the initial state initializer does not run again merely because a new prop arrives. Also avoid reading localStorage during the first render to choose a different login state from the server HTML. The server snapshot and the first browser render must agree for hydration.
After a login or logout action updates cookies, choose a server redirect or refresh path that obtains a new verified snapshot. If a client mutation flow needs an explicit router.refresh(), call it after the cookie-changing operation succeeds. It requests fresh route data; it does not turn client state into authority or invalidate every independent cache. Clear private client query data and ensure a delayed old-session response cannot repopulate the logged-out interface.
With Cache Components, place request-specific session reads behind an appropriate Suspense boundary rather than caching one currentUser globally. A server wrapper can await readSession and pass its DTO to this provider. Keep the boundary as narrow as the product allows. Independent tabs still need a deliberate refresh signal, focus revalidation or another synchronization policy; one tab updating its React context does not mutate another tab's memory.
Client module
"use client";
import { createContext, useContext, type ReactNode } from "react";
type SessionView = { userId: string; expiresAt: number } | null;
const SessionContext = createContext<SessionView>(null);
export default function SessionProvider({ session, children }: {
session: SessionView;
children: ReactNode;
}) {
return <SessionContext.Provider value={session}>{children}</SessionContext.Provider>;
}
export function useSessionView() {
return useContext(SessionContext);
}Server execution
import type { ReactNode } from "react";
import SessionProvider from "./session-provider";
import { readSession } from "@/lib/stateless-session";
export default async function SessionBoundary({ children }: { children: ReactNode }) {
const session = await readSession();
return <SessionProvider session={session}>{children}</SessionProvider>;
}Expiry, rotation and logout are different promises
Deleting a stateless cookie logs that browser out by stopping it from sending that cookie. It does not cryptographically invalidate a copied token that remains valid until its expiry. Rejecting one copied token immediately requires a denylist, session version, online introspection or another stateful check. Rotating the signing key can invalidate a broad set of tokens, but it is not a precise per-user logout operation.
Short-lived tokens bound the stale-credential window but create a renewal requirement. Refresh-token rotation with replay detection normally tracks a token family or equivalent state. Calling a long-lived signed cookie stateless does not grant replay detection for free. A meaningful design explains absolute lifetime, renewal rules, clock tolerance and which authority decides whether the user still exists or is still permitted.
Roles and tenant membership embedded in a valid token can become stale before the token expires. Cryptographic validity means the issuer signed those claims, not that the business permission is unchanged right now. If immediate removal of access is required, consult current authorization state or use an appropriate policy version check. If the system deliberately accepts a short delay, state that policy and test its boundary.
The jose operations use Web Crypto-compatible primitives, but Node and Edge runtimes still differ in available libraries and platform limits. Keep the session module independent of Node-only database drivers when targeting an Edge-compatible path, and verify the actual adapter. A successful signing operation in Node does not prove every imported authentication dependency runs at the Edge.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEJWT means encrypted.
- A more accurate model
A typical signed JWS JWT is readable by its holder; JWE is a separate encryption format.
- How to check it
RFC 7519, RFC 7516 and the jose SignJWT/EncryptJWT primary documentation.
- CLAIM TO CHALLENGEStateless sessions require no state and support free immediate revocation.
- A more accurate model
Tokens, keys and policy are state. Immediate per-session revocation needs added state or an online authority.
- How to check it
The copied-token logout scenario in the authentication lesson.
- CLAIM TO CHALLENGEHttpOnly makes the session token unreadable by everyone and defeats every attack.
- A more accurate model
It prevents page JavaScript from reading that cookie. It does not encrypt claims, stop every authenticated request abuse or replace authorization.
- How to check it
Next.js authentication and data-security guides; distinguish cookie transport from resource permission.
- CLAIM TO CHALLENGEuseState(initialSession) automatically tracks fresh server props.
- A more accurate model
The initializer runs for that state instance, so later props require deliberate reconciliation or direct prop-derived context.
- How to check it
The session-provider example uses its current verified session prop directly.
Mistakes to catch in your own code
- Equating a localStorage flag with a verified session.
- Putting session secrets into public environment variables or query strings.
- Trusting an arbitrary returnTo URL.
- Caching currentUser globally across requests.
- Calling a signed JWS token encrypted or treating Base64url decoding as verification.
- Assuming stateless means no server secrets, no state or instant individual revocation.
- Initializing a provider once from server props and ignoring later refreshed props.
- Treating a bearer token as public just because it does not contain the signing secret.
Write it by hand
JavaScript logic playground
Evaluate a bounded session policy
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Input is {session,now,returnTo}; session is null or {userId,expiresAt,revoked}. now and expiresAt are integer timestamps.
- A session is valid only when userId is a nonempty string, revoked is false and expiresAt is greater than now.
- A return path must start with one slash, not two, and contain no backslash. Otherwise use /dashboard.
- Return {authenticated,userId,destination}; unauthenticated destination is /login.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Use a valid local destination
Input
{ "session": { "userId": "u1", "expiresAt": 200, "revoked": false }, "now": 100, "returnTo": "/cart?step=2" }Expected
{ "authenticated": true, "userId": "u1", "destination": "/cart?step=2" } - Expire at the exact boundary
Input
{ "session": { "userId": "u1", "expiresAt": 100, "revoked": false }, "now": 100, "returnTo": "/cart" }Expected
{ "authenticated": false, "userId": null, "destination": "/login" } - Reject an external redirect
Input
{ "session": { "userId": "u1", "expiresAt": 200, "revoked": false }, "now": 100, "returnTo": "//evil.example" }Expected
{ "authenticated": true, "userId": "u1", "destination": "/dashboard" } - Reject a revoked session
Input
{ "session": { "userId": "u1", "expiresAt": 200, "revoked": true }, "now": 100, "returnTo": "/dashboard" }Expected
{ "authenticated": false, "userId": null, "destination": "/login" }
Reveal the worked solution and reasoning
function solve(input) {
const s = input.session;
const authenticated = Boolean(s && typeof s.userId === "string" && s.userId.length > 0 && s.revoked === false && s.expiresAt > input.now);
const path = typeof input.returnTo === "string" && input.returnTo.startsWith("/") && !input.returnTo.startsWith("//") && !input.returnTo.includes("\\") ? input.returnTo : "/dashboard";
return { authenticated, userId: authenticated ? s.userId : null, destination: authenticated ? path : "/login" };
}Strictly greater expiry makes the boundary behavior deliberate.
This pure policy receives already-decoded data; it does not establish that a token is authentic.
Production return-URL validation should use a complete same-origin or explicit route allowlist policy for the application.
Verify it in a real Next.js application
Next.js application lab
Compare opaque and stateless sessions across server and client
Open the local application route /session after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Open /login and inspect the three practice identities and two session modes. This shipped selector is a credential-free test fixture. It intentionally does not establish a production password or OAuth authentication flow.
- Choose the opaque model, visit /session, and trace fx-lab-session through currentUser in lib/session.ts to the session record and current user record. Its cookie and server record expire after one hour.
- Choose the signed model and inspect lib/session-token.ts plus lib/signing-key.ts. The existing jose implementation verifies the algorithm, issuer, audience, required claims and five-minute lifetime. A request verifies claims without reading a session or user row; login still selects a seeded identity and task data still lives in the file store.
- Reload /session and inspect the cookie attributes and the public DTO passed to components/session-snapshot.tsx. The provider derives its value from incoming props, uses stable ISO expiry text and never receives a raw token.
- Open a second tab on /session, sign out in the first, then use Refresh server snapshot in the second. Observe that manual router.refresh obtains a new verified DTO. This lab does not automatically broadcast login or logout to every tab.
- In this local fixture only, preserve your own stateless cookie, sign out and restore that copy before expiry. Compare the successful replay with an opaque cookie whose session record was deleted on logout.
- Run the existing token tests for changed payloads, wrong keys, expiry, future issuance, issuer/audience mismatches and missing claims. Use the browser session tests to observe cookie persistence, tamper rejection and provider refresh through real requests.
- Implementation extension: reject delayed responses from a previous identity, clear or partition private client caches, and broadcast session changes between tabs. Add refresh rotation or individual revocation only after defining the required shared state and reuse policy.
Check the behavior
- Anonymous protected reads fail even if the client presentation is manipulated; each real server entry point obtains its own verified identity.
- A signed-cookie login does not add a session row, and a reload restores the verified public view. It still depends on a stable server signing key and a trusted identity-issuance step.
- Tokens and signing keys are absent from page props and client context. Browser JavaScript cannot read the HttpOnly cookie; the browser still sends it on eligible requests.
- After ordinary logout, the next request from that browser is unauthenticated. Restoring a copied unexpired signed cookie succeeds under the stated stateless contract; replaying the revoked opaque cookie fails.
- Tampered, expired and wrongly scoped tokens fail verification. Refreshing the UI does not renew a token or make embedded roles current.
- The first client session render agrees with the server snapshot, and manual refresh replaces stale context after another tab signs out.
- Automatic cross-tab updates, late-response rejection, refresh-token rotation and immediate individual stateless-token revocation are explicit extensions, not shipped behavior.
Review the application reasoning
The lesson contains a minimal general-purpose session helper; the runnable lab uses its own five-minute training-token contract and two selectable session models. Compare those contracts deliberately rather than assuming every sample has identical claim fields or lifetime.
The practice account selector is not production authentication. Signature verification establishes the issued claims, not current authorization freshness: a signed role or tenant may remain stale until expiry unless the application consults a current authority.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01How do cookie sessions and bearer tokens compare?
A cookie is a browser transport mechanism, while a session or token defines the identity proof. An opaque cookie-backed session permits centralized revocation; a self-contained token changes storage and verification trade-offs.
I consider browser and nonbrowser clients, revocation, expiry, cross-site behavior and token exposure. I do not claim that JWT automatically makes a design stateless, secure or scalable.
Follow-up questions
- What happens after a token is stolen?
- Which component owns renewal?
- Data securityOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
02Does HttpOnly solve every authentication attack?
No. It prevents JavaScript from directly reading that cookie, but malicious code may still make authenticated requests in the user's browser. It also does not decide whether a user can access a specific record.
I combine appropriate transport and cookie policy with application validation, output safety and server authorization. The protections address different failure modes.
Follow-up questions
- Why does a write endpoint still need authorization?
- How would you handle a cross-site mutation request?
- Data securityOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
03Is checking the session in a layout enough?
A layout check controls a rendered route experience, but it is not the sole boundary for private reads and writes. Each callable server entry and DAL must enforce the relevant checks.
I also account for layout reuse and session changes after navigation. Data access should not rely on a layout having rerun recently.
Follow-up questions
- What happens when permissions change while a tab stays open?
- How do direct action requests behave?
- Data securityOfficial documentation
- ProxyOfficial documentation
04How would you prove logout works?
I verify the session is revoked or expired according to the design, the cookie is removed, and a fresh protected request fails. Then I check browser history and client caches for stale private data.
A UI-only test that sees a login button proves only presentation. I also exercise a previously authenticated request and an in-flight response arriving after logout.
Follow-up questions
- What should another open tab show?
- How does stateless-token logout differ?
- Data securityOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
05How can a Next.js session survive a reload without storing sessions in a database?
The server can issue a signed, short-lived cookie containing minimal claims. The browser stores and automatically sends it on matching requests; the server verifies its signature, issuer, audience and lifetime before deriving a user view.
The token and key policy are still state. This removes a per-session lookup from the basic verification path, but does not solve account authentication, permission freshness or individual immediate revocation.
Follow-up questions
- Where does the signing secret live?
- What happens if two replicas use different keys?
- jose library and runtime supportOfficial documentation
- jose SignJWTOfficial documentation
- jose jwtVerifyOfficial documentation
- Next.js authentication guideOfficial documentation
06Can a user read or change a signed JWT?
A typical signed JWS JWT is encoded, not encrypted, so its holder can read the claims. Editing those claims invalidates the signature when the server verifies correctly. Decoding alone establishes no trust.
JWE provides encryption when confidentiality is required. Both forms can still be sensitive bearer credentials; neither should contain server signing secrets or be treated as harmless public data.
Follow-up questions
- How does HS256 differ from asymmetric signing?
- Does encryption provide immediate logout revocation?
- JSON Web Token standardOfficial documentation
- JSON Web Encryption standardOfficial documentation
- jose EncryptJWTOfficial documentation
07How do you keep server and client authentication state synchronized without a hydration flash?
I verify the request cookie on the server, render a minimal session DTO and give that same snapshot to the client provider for its first render. I do not choose a contradictory initial state from localStorage.
After login or logout I obtain fresh server route data through the chosen redirect or refresh flow, and ensure the provider uses updated props. I clear private client caches and handle stale in-flight responses separately.
Follow-up questions
- Why can useState(initialSession) become stale?
- Does router.refresh invalidate every query library cache?
- Hydration error diagnosisOfficial documentation
- React hydrateRootOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
- TanStack Query advanced server renderingOfficial documentation
08Does deleting a signed session cookie revoke every copy of its token?
No. It removes the cookie from that browser context. A copied token may remain cryptographically valid until expiry unless the server consults revocation state or changes the applicable verification key policy.
For immediate per-user or per-session revocation I need additional state or an online authority. Short lifetimes reduce the window but do not make it zero, and refresh rotation with replay detection has its own state requirements.
Follow-up questions
- What would a denylist store?
- How would you revoke a changed tenant role immediately?
- jose jwtVerifyOfficial documentation
- jose JWT claim verification optionsOfficial documentation
- Next.js authentication guideOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Data securityOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
- Forms with Server ActionsOfficial documentation
- ProxyOfficial documentation
- jose library and runtime supportOfficial documentation
- jose SignJWTOfficial documentation
- jose jwtVerifyOfficial documentation
- jose JWT claim verification optionsOfficial documentation
- JSON Web Token standardOfficial documentation
- JSON Web Encryption standardOfficial documentation
- Next.js authentication guideOfficial documentation
- jose EncryptJWTOfficial documentation
- Hydration error diagnosisOfficial documentation
- React hydrateRootOfficial documentation
- TanStack Query advanced server renderingOfficial documentation