Next.js › Security Best Practices in Next.js
How would you protect server actions from being called with malicious or unauthorized data, since they can be invoked directly from the client?
AdvancedAnswer
You always validate and sanitize the incoming data inside the server action itself using a schema validation library, never trust that data matches what your form actually intended to send, and check that the currently authenticated user is actually authorized to perform that specific action before making any changes.
'use server';
import { z } from 'zod';
const schema = z.object({ postId: z.string(), text: z.string().max(500) });
export async function addComment(formData) {
const session = await getSession();
if (!session) throw new Error('Not authenticated');
const result = schema.parse({ postId: formData.get('postId'), text: formData.get('text') });
await db.comment.create({ data: { ...result, userId: session.user.id } });
}Real-world example A comment feature validates both the shape of incoming data and confirms the user is properly authenticated inside its server action, preventing a malicious actor from bypassing the form and submitting harmful data directly.