What are Next.js Server Actions best practices?
Why Interviewers Ask This
This tests whether you can apply Next.js knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Server Actions are powerful but require careful implementation: 1. Security — validate inputs: always validate server action inputs — never trust client data: async function createUser(formData: FormData) { "use server"; const name = formData.get("name"); if (typeof name !== "string" || name.length < 2) throw new Error("Invalid name"); }. Use Zod for schema validation. 2. Authentication — verify the caller: const session = await getServerSession(); if (!session) throw new Error("Unauthorized");. Never assume the caller is authenticated. 3. CSRF protection: Next.js provides built-in CSRF protection for Server Actions — they only accept POST requests with specific headers. Don't use them as GET endpoints. 4. Return consistent shapes: type ActionResult = { success: boolean; data?: any; error?: string }; async function createUser(fd: FormData): Promise<ActionResult> { try { ... return { success: true, data: user }; } catch(e) { return { success: false, error: e.message }; } }. 5. Revalidate after mutations: call revalidatePath() or revalidateTag() after data changes to refresh cached data. 6. Progressive enhancement: Server Actions work as HTML form actions without JavaScript. Design forms to work without JS first. 7. Optimistic updates: use useOptimistic hook to show immediate UI feedback while the action runs. 8. Loading states: use useFormStatus to disable submit button during pending state. 9. Error boundaries: wrap form components in error boundaries for action errors.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is the Next.js App Router middleware in depth?
Next
What is Next.js OpenGraph image generation?
More Next.js Questions
View all →- Intermediate How does Next.js caching work in the App Router?
- Intermediate What are Server Components vs Client Components trade-offs?
- Intermediate What is React Suspense and streaming in Next.js?
- Intermediate How do you implement authentication in Next.js?
- Intermediate What is Next.js App Router data fetching patterns?