Authentication in Next.js spans middleware, Server Components, and route handlers. Interviewers want layered security — never trust the client alone.
Common Interview Questions
Q: Where to verify sessions?
Answer: Middleware for coarse route protection (fast redirect). Server Components and Server Actions for authoritative checks before data access. Client checks are UX only.
Q: Auth.js (NextAuth) pattern?
Answer: Central auth config with providers, callbacks, and session strategy (JWT or database sessions).
import { auth } from "@/auth";
export default async function Dashboard() {
const session = await auth();
if (!session) redirect("/login");
return <DashboardUI user={session.user} />;
}
Q: HTTP-only cookies vs localStorage JWT?
Answer: Prefer HTTP-only secure cookies for session tokens — not accessible to XSS. localStorage tokens are easier to steal via script injection.
Q: Protecting Server Actions?
Answer: Call auth() or validate session inside every action. Middleware alone is insufficient if actions are invoked directly.
Key Points for Interviews
-
Defense in depth: middleware + server checks
-
Never expose secrets to Client Components
-
Session refresh and rotation for long-lived apps
-
OAuth flows handled by auth libraries
-
Role-based access in Server Actions and RSC
