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

기본 서버 액션 폼

Next.js Server Actions를 사용하여 데이터를 서버에 직접 제출하는 대화형 폼을 만듭니다.

기본 서버 액션 폼은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!

자주 묻는 질문

“기본 서버 액션 폼” 강의는 무료인가요?

네 — “기본 서버 액션 폼” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.

“기본 서버 액션 폼”에서 뭘 배우나요?

Next.js Server Actions를 사용하여 데이터를 서버에 직접 제출하는 대화형 폼을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“기본 서버 액션 폼” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 기본 서버 액션 폼
  2. 데이터 변경 및 재검증
  3. 액션의 오류 처리
  4. Server Actions를 활용한 낙관적 UI와 대기 상태
← Next.js 15 Fullstack (App Router + Server Actions)(으)로 돌아가기