0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lección

Validación y gestión de errores en Server Actions

Cree Server Actions robustas validando la entrada con Zod, devolviendo estados de error estructurados y mostrándolos en sus formularios con useActionState.

Validación y gestión de errores en Server Actions es una lección gratuita de Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit. Esta es la lección 3 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack (App Router + Server Actions), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Validate Server Actions?

Server Actions receive data straight from the client, which can never be trusted. Validation guards against malformed input, injection, and broken business rules before anything touches your database.

Reading FormData

A Server Action bound to a form receives a FormData object. You read fields by name, but every value arrives as a string.

'use server';
export async function createPost(formData: FormData) {
  const title = formData.get('title');
  const views = formData.get('views');
}

Defining a Zod Schema

Zod declares the shape and rules of your data. coerce converts string form values into the right types automatically.

import { z } from 'zod';
const PostSchema = z.object({
  title: z.string().min(3, 'Title too short'),
  views: z.coerce.number().int().min(0)
});

Safe Parsing

Use safeParse instead of parse so validation failures return a result object rather than throwing. Inspect success to branch.

const parsed = PostSchema.safeParse({
  title: formData.get('title'),
  views: formData.get('views')
});
if (!parsed.success) {
  // handle errors
}

Returning a Structured Error State

Rather than throwing, return an object describing what went wrong. Field-level messages let the UI show errors next to the right input.

if (!parsed.success) {
  return {
    errors: parsed.error.flatten().fieldErrors,
    message: 'Validation failed'
  };
}

Wiring useActionState

On the client, useActionState tracks the value your action returns. It gives you the latest state and a wrapped action to pass to the form.

'use client';
const [state, formAction] = useActionState(createPost, { errors: {} });

Displaying Field Errors

Render messages from state.errors beneath each field so users see exactly what to fix.

<input name="title" />
{state.errors?.title && (
  <p className="error">{state.errors.title[0]}</p>
)}

Catching Unexpected Errors

Validation handles bad input, but database or network calls can still fail. Wrap them in try/catch and return a friendly message instead of leaking internals.

try {
  await prisma.post.create({ data: parsed.data });
} catch (e) {
  return { message: 'Database error. Please try again.' };
}

Revalidating on Success

After a successful write, call revalidatePath so cached pages refetch and the new data appears immediately.

import { revalidatePath } from 'next/cache';
revalidatePath('/posts');
return { message: 'Post created!' };

Never Trust the Client

Client-side validation improves UX but can be bypassed. Always re-validate on the server. The Server Action is your real security boundary.

Best Practices

Robust actions follow a pattern:

  • Validate with Zod safeParse
  • Return structured field errors
  • Surface them with useActionState
  • Wrap side effects in try/catch
  • Revalidate on success

Quick Check

Test your validation knowledge.

Recap

You hardened your Server Actions:

  • Validate FormData with a Zod schema and safeParse
  • Return structured errors and a message
  • Track them with useActionState and render per field
  • Catch runtime failures and revalidate on success

Your forms now fail gracefully and stay secure.

Preguntas frecuentes

¿La lección «Validación y gestión de errores en Server Actions» es gratis?

Sí — el texto completo de «Validación y gestión de errores en Server Actions» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack (App Router + Server Actions), actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 3 lecciones en total.

¿Qué aprenderé en «Validación y gestión de errores en Server Actions»?

Cree Server Actions robustas validando la entrada con Zod, devolviendo estados de error estructurados y mostrándolos en sus formularios con useActionState. Practicas Next.js 15 Fullstack (App Router + Server Actions) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Next.js 15 Fullstack (App Router + Server Actions)?

No se requiere experiencia previa. Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 3.

¿Cuánto tiempo toma la lección «Validación y gestión de errores en Server Actions»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack (App Router + Server Actions)?

Sí. Cada lección de Next.js 15 Fullstack (App Router + Server Actions) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Actualizaciones optimistas de la UI
  2. Carga de archivos con Actions
  3. Validación y gestión de errores en Server Actions
← Volver a Next.js 15 Fullstack (App Router + Server Actions)