QA
Intermediate LevelAuthentication & Authorization

How do you handle authentication securely in Next.js App Router Server Actions and Middleware?

❓ Interview Prompt: Explain Next.js App Router Server Actions security, reading httpOnly cookies, server-side session validation, and CSRF protection.

In Next.js App Router, Server Actions expose POST endpoints accessible via public HTTP requests. Treating Server Actions like client-side functions without explicit authentication validation creates major vulnerabilities!

Next.js Auth Architecture Rules:

1
Never Trust Client Inputs: Always validate authentication inside the Server Action body using 'cookies()' or session helpers.
2
HttpOnly Cookie Retrieval: Read httpOnly session cookies server-side.
3
Session Verification: Verify session token against Redis/DB before performing database mutations.

Code Implementation Example

typescript
'use server'

import { cookies } from 'next/headers';
import { verifySession } from '@/lib/auth';

export async function deletePostAction(postId: string) {
  // 1. Extract session token from httpOnly cookie server-side
  const cookieStore = await cookies();
  const sessionToken = cookieStore.get('session_id')?.value;

  // 2. Validate session & permissions
  const session = await verifySession(sessionToken);
  if (!session || !session.user.permissions.includes('posts:delete')) {
    throw new Error('Unauthorized');
  }

  // 3. Perform database deletion safely
  await db.posts.delete(postId);
}
💡Server-side session validation inside Next.js App Router Server Action.
🎯 Interview Key Takeaway

Always validate session tokens server-side inside Next.js Server Actions using httpOnly cookie getters.

#Next.js#Server Actions#Cookies#Security#Intermediate
Back to all Authentication & Authorization Questions→

More Authentication & Authorization Interview Questions

Beginner LevelAuthentication & Authorization

Compare JWT Token Authentication versus Stateful Sessions, and explain OAuth 2.0 PKCE flow.

Beginner LevelAuthentication & Authorization

What is the fundamental difference between Authentication (AuthN) and Authorization (AuthZ)?

Beginner LevelAuthentication & Authorization

Why should passwords never be stored in plain text and how do bcrypt and Argon2id work?