Course contentsShow
← React
Lesson 1608 of 2,39639. Server Components in PracticeFree lesson

Security: Validating Input on the Server

Always validate Server Action inputs server-side—never trust client data, even from your own components.

Security: Validating Input on the Server

What you'll learn: Why you must always validate data in Server Actions on the server, even when it comes from your own React components.


Never Trust the Client

When building Server Actions, it's tempting to think: "This form is in my own component with controlled inputs—the data is safe!" This is a dangerous assumption. Anyone with browser DevTools can modify the data being sent to your server, bypass your client-side validation, or call your Server Action directly with malicious payloads.

Think of it like a restaurant kitchen: even if your waiter (the client) seems trustworthy, the chef (the server) must still verify every order before cooking. The waiter could be compromised, or someone could sneak into the kitchen with a fake order.

Always Validate Server-Side

Every Server Action must treat incoming data as untrusted:

'use server'

async function updateUserProfile(formData: FormData) {
  // ❌ DANGEROUS: Trusting client data
  // const age = formData.get('age');
  // await db.users.update({ age });

  // ✅ SAFE: Validate everything
  const age = formData.get('age');
  
  if (!age || typeof age !== 'string') {
    throw new Error('Invalid age');
  }
  
  const ageNum = parseInt(age, 10);
  
  if (isNaN(ageNum) || ageNum < 0 || ageNum > 120) {
    throw new Error('Age must be between 0 and 120');
  }
  
  await db.users.update({ age: ageNum });
}

Client-side validation improves UX, but server-side validation enforces security. Use validation libraries like Zod or Yup for complex schemas, but never skip this step.

Key Takeaway: Client-side validation is for user experience; server-side validation is for security. Always validate all inputs in Server Actions—the client boundary is a trust boundary.