0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · レッスン

Server Actionsのバリデーションとエラーハンドリング

Zodで入力を検証し、構造化されたエラー状態を返して、useActionStateでフォームに表示する堅牢なServer Actionsを構築します。

「Server Actionsのバリデーションとエラーハンドリング」はCoddyKit上の無料Next.js 15 Fullstack (App Router + Server Actions)レッスンです。 これはレッスン3/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはNext.js 15 Fullstack (App Router + Server Actions)学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Next.js 15 Fullstack (App Router + Server Actions)コースには全3レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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.

よくある質問

「Server Actionsのバリデーションとエラーハンドリング」レッスンは無料ですか?

はい。「Server Actionsのバリデーションとエラーハンドリング」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Next.js 15 Fullstack (App Router + Server Actions)コースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack (App Router + Server Actions)コースには全3レッスンが含まれています。

「Server Actionsのバリデーションとエラーハンドリング」で何を学びますか?

Zodで入力を検証し、構造化されたエラー状態を返して、useActionStateでフォームに表示する堅牢なServer Actionsを構築します。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack (App Router + Server Actions)を演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Next.js 15 Fullstack (App Router + Server Actions)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのNext.js 15 Fullstack (App Router + Server Actions)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/3です。

「Server Actionsのバリデーションとエラーハンドリング」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このNext.js 15 Fullstack (App Router + Server Actions)レッスンでコードを書いて実行できますか?

はい。すべてのNext.js 15 Fullstack (App Router + Server Actions)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 楽観的UI更新
  2. Actionsによるファイルアップロード
  3. Server Actionsのバリデーションとエラーハンドリング
← Next.js 15 Fullstack (App Router + Server Actions)に戻る