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

基本的なServer Actionフォーム

Next.js Server Actionsを使い、サーバーに直接データを送信するインタラクティブなフォームを作成します

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

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

Intro to Server Actions

Welcome to Server Actions! This powerful Next.js 15 feature allows you to define functions that run directly on the server, callable from your client components.

Think of them as a way to send data to your server without needing to create a separate API route. They simplify data mutations and form submissions.

Why Use Server Actions?

Server Actions offer several key benefits for your Next.js applications:

  • Simplified Data Mutations: Directly call server-side code from your forms.
  • Reduced Client-Side JS: Less JavaScript needs to be sent to the browser.
  • Improved Performance: Actions run closer to your database, potentially reducing latency.
  • Automatic Revalidation: They can automatically update cached data after a successful mutation (more on this in a later lesson!).

Defining a Server Action

A Server Action is an async function marked with the "use server" directive. This directive tells Next.js to treat the function as server-only code.

You can define actions directly in your components or in a separate file (e.g., app/actions.js) and import them.

// app/actions.js
"use server";

export async function createItem(formData) {
  const itemName = formData.get("itemName");
  console.log(`Server received: ${itemName}`);
  // In a real app, you'd save 'itemName' to a database
}

Connecting Form to Action

To link an HTML <form> element to a Server Action, you simply pass the action function directly to the form's action prop. It's that easy!

When the form is submitted, Next.js automatically invokes the specified Server Action.

// app/page.js
import { createItem } from './actions';

export default function Page() {
  return (
    <form action={createItem}>
      <label htmlFor="item">New Item:</label>
      <input type="text" id="item" name="itemName" required />
      <button type="submit">Add Item</button>
    </form>
  );
}

Accessing Form Data

When a form submits to a Server Action, the action function automatically receives a FormData object as its first argument.

You can use formData.get('fieldName') to retrieve the value of an input based on its name attribute.

// app/actions.js
"use server";

export async function processForm(formData) {
  const username = formData.get("username");
  const email = formData.get("email");
  const age = formData.get("age");

  console.log(`User: ${username}, Email: ${email}, Age: ${age}`);
  // Perform server-side logic, e.g., save user to database
}

Full Form Example

Let's combine what we've learned into a simple guestbook entry form. The Server Action will log the guest's message.

Remember, this code is for a Next.js environment and isn't runnable as a standalone JS file.

// app/actions.js
"use server";

export async function addGuestbookEntry(formData) {
  const message = formData.get("message");
  console.log(`New guestbook entry: ${message}`);
  // In a real app, save to DB and revalidate cache
}

// app/page.js
import { addGuestbookEntry } from './actions';

export default function GuestbookPage() {
  return (
    <div>
      <h1>Guestbook</h1>
      <form action={addGuestbookEntry}>
        <textarea name="message" rows="4" cols="30" placeholder="Your message..." required></textarea>
        <button type="submit">Sign Guestbook</button>
      </form>
    </div>
  );
}

Handling Multiple Inputs

The FormData object efficiently captures all inputs within your form that have a name attribute. You can access them individually.

  • formData.get('inputName'): Gets the first value for a given name.
  • formData.getAll('inputName'): Returns an array of all values for inputs with the same name (useful for multiple checkboxes).
  • formData.entries(): Returns an iterator for all key/value pairs.

User Feedback: Loading States

When a form is submitting, it's good practice to provide visual feedback to the user. Next.js, along with React, provides the useFormStatus hook for this.

useFormStatus tells you if the parent <form> is currently submitting, allowing you to disable buttons or show a spinner.

// app/page.js (inside a component, e.g., SubmitButton.js)
import { useFormStatus } from "react-dom";

function SubmitButton() {
  const { pending } = useFormStatus(); // Gets status from parent <form>

  return (
    <button type="submit" disabled={pending}>
      {pending ? "Submitting..." : "Submit"}
    </button>
  );
}

// In your page.js:
// import { addGuestbookEntry } from './actions';
// export default function Page() {
//   return (
//     <form action={addGuestbookEntry}>
//       {/* ... other inputs */}
//       <SubmitButton />
//     </form>
//   );
// }

Quick Check

Which statements about basic Next.js Server Action forms are correct?

Recap & Next Steps

Great job! You've learned the fundamentals of creating basic forms with Next.js Server Actions:

  • Server Actions are server-side functions marked with "use server".
  • They simplify form submissions by allowing you to pass the action directly to a form's action prop.
  • Form data is accessed within the action via a FormData object.
  • The useFormStatus hook helps implement loading indicators.

Next, we'll dive into how Server Actions can mutate data and automatically revalidate your UI!

よくある質問

「基本的なServer Actionフォーム」レッスンは無料ですか?

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

「基本的なServer Actionフォーム」で何を学びますか?

Next.js 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)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「基本的なServer Actionフォーム」レッスンにはどのくらい時間がかかりますか?

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

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

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

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

  1. 基本的なServer Actionフォーム
  2. データの変更と再検証
  3. Actionsでのエラー処理
  4. Server Actionsによる楽観的UIと保留状態
← Next.js 15 Fullstack (App Router + Server Actions)に戻る