Next.js & App Router (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
Security in Server Actions: Protection Against Unauthorized Invocation.
senior LevelCode ExampleState ManagementSecurity & AuthSystem Design
In Simple Words: Treat Server Actions exactly like public REST POST endpoints!
- Attackers can invoke Server Actions directly by sending POST requests with arbitrary payloads.
- Mandatory Security Checklist:
- Always verify user authentication inside the action:
typescript
const session = await getSession(); if (!session) throw new Error('Unauthorized'); - Always validate input data using a schema validator like Zod:
typescript
const validated = CommentSchema.safeParse(data); if (!validated.success) throw new Error('Invalid data'); - Authorize ownership: verify that the user owns the record they are modifying.
- Always verify user authentication inside the action: