Q1: How do you implement Authentication in the App Router?
Auth.js (NextAuth v5): The standard solution. It supports OAuth, email magic links, and credentials.
Implementation:
- Config: Create an
auth.jsfile exporting the config. - Middleware: Use
middleware.jsto protect routes globally. - Server Side: Use
auth()helper to get the session in RSCs. - Client Side: Use
SessionProvideranduseSessionhook.
Q2: How does Middleware protect routes?
Middleware runs before the request hits the page. You can check for a session token and redirect if missing.
import { auth } from "@/auth"
export default auth((req) => {
const isLoggedIn = !!req.auth
const isOnDashboard = req.nextUrl.pathname.startsWith('/dashboard')
if (isOnDashboard && !isLoggedIn) {
return Response.redirect(new URL('/login', req.nextUrl))
}
})
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}
Q3: Where should you store sensitive data like API keys?
Environment Variables: Store them in .env.local.
Server-only: Variables without the NEXT_PUBLIC_ prefix are only available on the server. This prevents accidental leakage to the client bundle.
Best Practice: Use the server-only package to ensure a module that handles sensitive data (like database connection) is never imported into a Client Component.
import 'server-only'
// ... database logic ...
Q4: What is RBAC (Role-Based Access Control) and how do you implement it?
Concept: Restricting access based on the user's role (e.g., Admin, Editor, User).
Implementation:
- Add a
rolefield to your User database model. - Include the role in the session callback in
auth.jsso it's available on the client. - Check the role in Middleware or Server Components.
// In a Server Component
const session = await auth();
if (session?.user?.role !== 'admin') {
redirect('/unauthorized');
}
Q5: How do you handle CSRF protection in Next.js?
Server Actions: Next.js Server Actions automatically include CSRF protection. The framework generates a hidden token for every action submission.
API Routes: If you are building manual API routes (route.js), you are responsible for CSRF protection if they are called from a browser. However, since Next.js encourages Server Actions for mutations, this is less of a concern for modern apps.