[Next.js] Router Handler & Server Action

API Route Handler

클라이언트가 서버에 데이터를 요청하거나 전송할 때 사용하는 엔드포인트를 정의하고, 어떤 동작을 할지 정의하기위해 사용할 수 있다.

즉, 클라이언트가 서버에 GET, POST, PUT, DELETE, PATCH 같은 HTTP 메서드 요청을 보낼 때 요청을 어떻게 보내고 처리한 값을 받을지 작성할 수 있다.

 

 

API Router Handler 예제

1) app/api/data/route.ts 파일 생성

- 컴포넌트에서 '/api/data' 경로로 fetch 요청을 보낸다

- 그럼 route.ts에서 정의해둔 실제 API URL로 네트워크 요청을 정의해둔 동작에 맞게 처리한다

// app/api/data/route.ts (서버에서 실행되는 코드)
export async function GET() {
  // 외부 API에 요청을 보내기 위해 fetch 사용
  const response = await fetch('https://api.example.com/data', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
  });

  const data = await response.json();

  // 클라이언트로 응답을 반환
  return new Response(JSON.stringify(data), {
    headers: { 'Content-Type': 'application/json' },
  });
}

 

2) 컴포넌트에서 사용한다

// 클라이언트에서 API 라우트 호출
fetch('/api/data', { method: 'GET' });

 

Server action

서버에서 실행되는 비동기 함수로, 폼 제출과 같은 데이터를 처리할 수 있게 한다.

사용하려면 파일 상단에 'use server' 지시어만 넣어주면 끝~

서버 컴포넌트와 클라이언트 컴포넌트 모두에서 사용할 수 있다.

서버 액션은 주로 CRUD 작업을 수행하기위해 사용한다.

"use server";
import { Product } from "@/type/product";
import { BASE_URL } from "@/constants/api";

export async function getProducts() {
  const res = await fetch(`${BASE_URL}/products`, {
    cache: "no-store",
  });
  const data: Product[] = await res.json();

  return { data };
}
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';

export async function addItemToCart(formData: FormData) {
  const { itemId, quantity } = formData.get('itemId'), formData.get('quantity');
  const cart = await fetch({...});

  revalidatePath('/cart');
  redirect('/cart');
}

'Next.js' 카테고리의 다른 글

[Next.js] Parallel Routes & Intercepting Routes  (1) 2024.09.29
[Next.js] Caching  (1) 2024.09.28
[Next.js] Asset 최적화  (1) 2024.09.27
[Next.js] Error UI, Error Handling  (0) 2024.09.27
[Next.js] Suspense, Loading UI, Streaming SSR  (0) 2024.09.27