▲ Next.js Intermediate

How do you implement authentication in Next.js?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Authentication in Next.js requires careful consideration of the App Router's server/client split. Recommended: NextAuth.js (Auth.js): the most popular authentication library for Next.js with built-in providers (Google, GitHub, credentials, etc.). Setup: // app/api/auth/[...nextauth]/route.ts import NextAuth from "next-auth"; import Google from "next-auth/providers/google"; const handler = NextAuth({ providers: [Google({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET })], callbacks: { session: ({ session, token }) => ({ ...session, userId: token.sub }) } }); export { handler as GET, handler as POST };. Session access in Server Components: import { getServerSession } from "next-auth"; const session = await getServerSession(authOptions);. Session access in Client Components: wrap with SessionProvider, use useSession() hook. Protecting routes with Middleware: // middleware.ts export function middleware(req) { const token = req.cookies.get("next-auth.session-token"); if (!token && req.nextUrl.pathname.startsWith("/dashboard")) { return NextResponse.redirect(new URL("/login", req.url)); } }. Custom auth: JWT tokens stored in httpOnly cookies; read in middleware and Server Components via cookies(). Clerk, Supabase Auth, Firebase Auth: third-party auth services with Next.js SDK support. Security considerations: always validate session on the server (not just client); use httpOnly cookies for session tokens; implement CSRF protection for Server Actions; rate-limit login attempts.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Next.js answers easy to follow.