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

Server-Side Validation

Validating form input on the server with Zod or similar libraries before processing.

Server-Side Validation

You'll learn how to validate form data securely on the server using libraries like Zod before processing it in Server Actions.

Why Server-Side Validation Matters

Even though you might validate forms on the client side (checking email formats, required fields, etc.), client-side validation can be bypassed. Anyone can open browser DevTools and send whatever data they want to your server. Server-side validation is your security checkpoint—it ensures that no matter what arrives at your server, you only process valid, safe data.

Think of it like airport security: even if passengers go through a preliminary check at the ticket counter (client validation), everyone still goes through the main security checkpoint (server validation) before boarding.

Validating with Zod in Server Actions

Inside a Server Action, you receive FormData and can validate it before doing anything with it:

'use server'

import { z } from 'zod'

const FormSchema = z.object({
  email: z.string().email('Invalid email address'),
  age: z.number().min(18, 'Must be 18 or older')
})

export async function submitForm(formData: FormData) {
  // Parse and validate
  const result = FormSchema.safeParse({
    email: formData.get('email'),
    age: Number(formData.get('age'))
  })

  if (!result.success) {
    return { errors: result.error.flatten().fieldErrors }
  }

  // Now safe to use result.data
  const { email, age } = result.data
  // Process validated data...
}

The validation happens on the server where the user cannot tamper with it. If validation fails, you return errors that your form can display.

Key Takeaway: Always validate form data on the server in Server Actions using libraries like Zod—client-side validation improves UX, but server-side validation ensures security and data integrity.