Next.js 15 Fullstack (App Router + Server Actions) · Lezione

Validazione e gestione degli errori nelle Server Actions

Crei Server Actions robuste validando gli input con Zod, restituendo stati di errore strutturati e mostrandoli nei form con useActionState.

Lezione 3 di 313 passaggi

Validazione e gestione degli errori nelle Server Actions è una lezione Next.js 15 Fullstack (App Router + Server Actions) gratuita su CoddyKit. Questa è la lezione 3 di 3. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack (App Router + Server Actions), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 3 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Gratis per iniziare

Impara TypeScript con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
22
Lezioni
88

Domande Frequenti

La lezione «Validazione e gestione degli errori nelle Server Actions» è gratuita?

Sì — il testo completo di «Validazione e gestione degli errori nelle Server Actions» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack (App Router + Server Actions), passa a CoddyKit PRO. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 3 lezioni in totale.

Cosa imparerò in «Validazione e gestione degli errori nelle Server Actions»?

Crei Server Actions robuste validando gli input con Zod, restituendo stati di errore strutturati e mostrandoli nei form con useActionState. Eserciti Next.js 15 Fullstack (App Router + Server Actions) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Next.js 15 Fullstack (App Router + Server Actions)?

Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack (App Router + Server Actions) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 3.

Quanto tempo richiede la lezione «Validazione e gestione degli errori nelle Server Actions»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack (App Router + Server Actions)?

Sì. Ogni lezione Next.js 15 Fullstack (App Router + Server Actions) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Aggiornamenti ottimistici dell'interfaccia
  2. Upload di file con le Actions
  3. Validazione e gestione degli errori nelle Server Actions
← Torna a Next.js 15 Fullstack (App Router + Server Actions)