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

Server Actions를 활용한 CRUD

Server Actions를 사용하여 데이터베이스에서 생성, 조회, 수정 및 삭제(CRUD) 작업을 수행합니다.

Server Actions를 활용한 CRUD은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

CRUD: Database Actions Made Easy

Welcome to CRUD operations with Next.js Server Actions! CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations for interacting with any database.

Server Actions provide a powerful way to perform these operations directly on the server, keeping your client-side bundle small and improving security.

Recap: Prisma & Server Actions

In the previous lesson, we set up Prisma. We'll use Prisma Client to interact with our database. Remember, Server Actions are asynchronous functions that run on the server.

They can be defined directly in a component or in a separate actions.js file. We'll use a simple Post model for our examples.

Create: Adding New Data

Let's start with Create. This involves adding a new record to your database. We'll create a simple form that uses a Server Action to add a new post.

Notice how the form's action attribute directly calls our server function. This avoids client-side JavaScript for form submission.

Create: Code Example

Here's how to create a new post using a Server Action. We import our Prisma client and use its create method.

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export default function CreatePostPage() {
  async function createPost(formData: FormData) {
    'use server';
    const title = formData.get('title') as string;
    const content = formData.get('content') as string;

    await prisma.post.create({
      data: { title, content, published: false },
    });

    revalidatePath('/posts'); // Refresh the posts list
  }

  return (
    <form action={createPost}>
      <input type="text" name="title" placeholder="Title" />
      <textarea name="content" placeholder="Content"></textarea>
      <button type="submit">Add Post</button>
    </form>
  );
}

Read: Fetching Existing Data

The Read operation retrieves data from your database. In Next.js App Router, you can fetch data directly in Server Components.

This means your data fetching logic runs on the server, before the component is sent to the client, improving initial load times.

Read: Code Example

Here's a Server Component that fetches all posts and displays them. The await prisma.post.findMany() call runs entirely on the server.

import { prisma } from '@/lib/prisma';

export default async function PostsPage() {
  const posts = await prisma.post.findMany();

  return (
    <div>
      <h1>All Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <b>{post.title}</b>
            <p>{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

Update: Modifying Records

Update operations change existing records. You'll typically identify the record by its unique ID and then provide the new data.

Similar to Create, an update action can be triggered from a form submission or a button click, executing server-side logic.

Update: Code Example

This Server Action updates a post's published status. We identify the post by id and use Prisma's update method.

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function updatePostStatus(id: number, published: boolean) {
  'use server';

  await prisma.post.update({
    where: { id },
    data: { published: !published },
  });

  revalidatePath('/posts');
}

// Example usage in a component:
// <button onClick={() => updatePostStatus(post.id, post.published)}>
//   Toggle Publish
// </button>

Delete: Removing Data

Finally, Delete removes a record from the database. This is often triggered by a button and requires the record's unique identifier.

Always be careful with delete operations, as they are usually irreversible!

Delete: Code Example

Here's a Server Action for deleting a post. We use prisma.post.delete with a where clause to specify which record to remove.

import { prisma } from '@/lib/prisma';
import { revalidatePath } from 'next/cache';

export async function deletePost(id: number) {
  'use server';

  await prisma.post.delete({
    where: { id },
  });

  revalidatePath('/posts'); // Refresh the posts list
}

// Example usage in a component:
// <button onClick={() => deletePost(post.id)}>
//   Delete Post
// </button>

CRUD Operations Check

You've learned about the four core CRUD operations. Which operation is used to retrieve existing data from the database?

Recap: CRUD with Actions

Today, you mastered performing Create, Read, Update, and Delete (CRUD) operations using Next.js Server Actions and Prisma.

  • Create: Add new records.
  • Read: Fetch records from the database.
  • Update: Modify existing records.
  • Delete: Remove records.

Server Actions make these operations efficient and secure by running them directly on the server, often requiring revalidatePath to update the UI after changes. Next, we'll explore database schema migrations!

자주 묻는 질문

“Server Actions를 활용한 CRUD” 강의는 무료인가요?

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

“Server Actions를 활용한 CRUD”에서 뭘 배우나요?

Server Actions를 사용하여 데이터베이스에서 생성, 조회, 수정 및 삭제(CRUD) 작업을 수행합니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 2번째 강의입니다.

“Server Actions를 활용한 CRUD” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. Prisma ORM 설정
  2. Server Actions를 활용한 CRUD
  3. 데이터베이스 스키마 마이그레이션
  4. 데이터베이스 시딩과 연결 풀링
← Next.js 15 Fullstack (App Router + Server Actions)(으)로 돌아가기