0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lekcja

Walidacja i obsługa błędów w Server Actions

Twórz niezawodne Server Actions, walidując dane wejściowe za pomocą Zod, zwracając ustrukturyzowane stany błędów i wyświetlając je w formularzach za pomocą useActionState.

Walidacja i obsługa błędów w Server Actions to bezpłatna lekcja Next.js 15 Fullstack (App Router + Server Actions) na CoddyKit. To lekcja 3 z 3. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Next.js 15 Fullstack (App Router + Server Actions), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Next.js 15 Fullstack (App Router + Server Actions) zawiera 3 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Walidacja i obsługa błędów w Server Actions” jest bezpłatna?

Tak — pełny tekst „Walidacja i obsługa błędów w Server Actions” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Next.js 15 Fullstack (App Router + Server Actions), przejdź na CoddyKit PRO. Kurs Next.js 15 Fullstack (App Router + Server Actions) zawiera 3 lekcji w sumie.

Co nauczysz się w „Walidacja i obsługa błędów w Server Actions”?

Twórz niezawodne Server Actions, walidując dane wejściowe za pomocą Zod, zwracając ustrukturyzowane stany błędów i wyświetlając je w formularzach za pomocą useActionState. Ćwiczysz Next.js 15 Fullstack (App Router + Server Actions) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Next.js 15 Fullstack (App Router + Server Actions)?

Nie wymagamy żadnego doświadczenia. Next.js 15 Fullstack (App Router + Server Actions) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 3.

Ile czasu zajmuje lekcja „Walidacja i obsługa błędów w Server Actions”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Next.js 15 Fullstack (App Router + Server Actions)?

Tak. Każda lekcja Next.js 15 Fullstack (App Router + Server Actions) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Optymistyczne aktualizacje interfejsu
  2. Przesyłanie plików za pomocą akcji
  3. Walidacja i obsługa błędów w Server Actions
← Powrót do Next.js 15 Fullstack (App Router + Server Actions)