Server Actionsによるフルスタックフォーム
Server Actionsを利用してフォーム送信をサーバー上で直接処理し、データの変更処理を簡潔にします。
「Server Actionsによるフルスタックフォーム」はCoddyKit上の無料Next.js 15 Fullstack Web Appsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはNext.js 15 Fullstack Web Apps学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Next.js 15 Fullstack Web Appsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
What are Server Actions?
Server Actions in Next.js 15 allow you to run server-side code directly from your React components. They are a powerful feature that simplifies data mutations and backend interactions.
Think of them as tiny, direct connections to your server logic, without needing to create separate API routes for every backend task.
Forms and Server Actions
One of the primary uses for Server Actions is handling form submissions. When you link an HTML <form> element to a Server Action, the browser automatically sends the form data to your server-side function.
- The
actionattribute of the<form>points directly to your Server Action function. - This eliminates the need for client-side JavaScript to capture and send form data, making forms simpler and more robust.
Defining Your First Action
A Server Action is simply an asynchronous JavaScript function marked with the "use server" directive. This directive tells Next.js that the function should be executed on the server.
You can define Server Actions directly within your React components (if they are Server Components) or in separate files for better organization.
Basic Server Action Example
Let's create a simple form that takes a username. When submitted, a Server Action will log the username on the server. Notice the "use server" at the top of the function.
// app/page.js
// This async function is our Server Action
async function processUsername(formData) {
"use server"; // Marks this function to run on the server
const username = formData.get('username'); // Get value by input's 'name' attribute
console.log('Server received username:', username);
// In a real application, you'd typically save this to a database
}
export default function HomePage() {
return (
<div>
<h1>Enter Your Username</h1>
<form action={processUsername}> {/* Link form to the Server Action */}
<input type="text" name="username" placeholder="Your username" required />
<button type="submit">Submit</button>
</form>
</div>
);
}Accessing Form Data
When a form is submitted to a Server Action, the action receives a FormData object as its first argument. This object is a standard web API that contains all the key-value pairs from your form's input fields.
- Use
formData.get('fieldName')to retrieve the value of a specific input. - The
'fieldName'must match thenameattribute of your HTML input element (e.g.,<input name="username" />).
Redirecting After Submission
After a user successfully submits a form and your Server Action processes the data (e.g., saves it to a database), you often want to redirect them to another page, such as a confirmation or a list view.
Next.js provides a redirect function from next/navigation that you can call directly within your Server Action to navigate the user to a new route.
Action with Redirect Example
Let's enhance our form to redirect the user after a successful submission. Here, we'll redirect to a /success-page.
// app/page.js
import { redirect } from 'next/navigation'; // Import the redirect function
async function handleSubmit(formData) {
"use server";
const username = formData.get('username');
console.log('Processing username:', username);
// In a real app, you'd do database operations here
// After successful processing, redirect the user
redirect('/success-page');
}
export default function SignupPage() {
return (
<div>
<h1>Sign Up</h1>
<form action={handleSubmit}>
<input type="text" name="username" placeholder="Username" required />
<button type="submit">Register</button>
</form>
</div>
);
}
// Note: For this example to fully work, you would need an actual
// app/success-page/page.js file with some content.
Basic Error Handling
Server Actions can encounter errors, such as invalid input or database issues. You can use standard JavaScript try...catch blocks within your action to gracefully handle these potential problems.
For more advanced error feedback to the user, you might return data from the action to the client component or use a specialized form library.
Updating UI with Revalidation
After a Server Action successfully mutates data (e.g., adding a new post), your user interface might need to update to reflect this change. Next.js provides functions like revalidatePath or revalidateTag from next/cache.
These functions tell Next.js to re-fetch and re-render data for a specific path or a cached data tag, ensuring your users always see the latest information without a full page refresh.
Server Action Question
Consider the following Server Action and form in a Next.js App Router application:
// app/add-task/page.js
import { redirect } from 'next/navigation';
async function createTask(formData) {
"use server";
const taskTitle = formData.get('title');
if (taskTitle.length < 5) {
throw new Error('Task title must be at least 5 characters long.');
}
console.log('Creating task:', taskTitle);
// Simulate saving to database
redirect('/tasks');
}
export default function AddTaskPage() {
return (
<form action={createTask}>
<input type="text" name="title" placeholder="Task Title" />
<button type="submit">Add Task</button>
</form>
);
}Recap: Fullstack Forms
You've mastered how Server Actions simplify fullstack form handling in Next.js 15!
- Server Actions (`"use server"`) execute code directly on the server.
- HTML
<form action={yourAction}>automatically sendsFormDatato your action. - Access form fields using
formData.get('name'). - Use
redirectfromnext/navigationfor post-submission navigation. - Implement error handling with
try...catchwithin your actions. - Consider
revalidatePathorrevalidateTagto update UI after data mutations.
This pattern reduces boilerplate and streamlines your data mutation workflows.
AI チューターと学ぶ TypeScript — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 12
- レッスン
- 48
よくある質問
「Server Actionsによるフルスタックフォーム」レッスンは無料ですか?
はい。「Server Actionsによるフルスタックフォーム」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Next.js 15 Fullstack Web Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack Web Appsコースには全4レッスンが含まれています。
「Server Actionsによるフルスタックフォーム」で何を学びますか?
Server Actionsを利用してフォーム送信をサーバー上で直接処理し、データの変更処理を簡潔にします。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Next.js 15 Fullstack Web Appsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのNext.js 15 Fullstack Web Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「Server Actionsによるフルスタックフォーム」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このNext.js 15 Fullstack Web Appsレッスンでコードを書いて実行できますか?
はい。すべてのNext.js 15 Fullstack Web Appsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 制御コンポーネントと状態
- React Hook Formによるフォームバリデーション
- Server Actionsによるフルスタックフォーム
- ファイルアップロードとマルチパートフォーム処理