IT Developer/Next.js

Next.js 기초 <3. Next.js 15의 API Routes – 백엔드 없이 서버 기능 구현하기>

TEMA_ 2025. 3. 6. 19:13
반응형

넥스트 Next.js

3. Next.js 15의 API Routes – 백엔드 없이 서버 기능 구현하기 

 

안녕하세요! 태마입니다.

Next.js 기초 강좌입니다.

 

강좌의 경우 

1. 주제 간단 정리

2. 상세 주제 정리

으로 이루어져 있습니다.

 

넥스트 Next.js

포스팅 시작하겠습니다 :)


 

1. 주제 간단 정리

 

1. API Routes란?

Next.js 15에서는 서버리스(Serverless) 방식의 API를 쉽게 구현할 수 있도록 API Routes 기능을 제공한다.
이는 별도의 백엔드 서버 없이도 Next.js 내부에서 API를 생성하고 사용할 수 있는 기능이다.

📌 Next.js 15 API Routes의 특징
백엔드 없이 서버 기능 구현 가능 → Express, FastAPI 같은 별도의 서버 필요 없음
App Router 기반의 새로운 API Routes → 기존 Pages Router 방식(pages/api/)이 아닌 app/api/에서 API 정의
서버리스(Serverless) 방식 지원 → 클라우드 환경에서 자동 확장 가능
Middleware 및 인증(NextAuth.js)과 쉽게 연동 가능
GET, POST, PUT, DELETE 등의 HTTP 메서드 지원

기존 방식과 Next.js 15의 API Routes 비교

구분Pages Router (pages/api/)App Router (app/api/)

폴더 위치 pages/api/ app/api/
라우팅 방식 파일 기반 자동 라우팅 파일 기반 자동 라우팅
서버 컴포넌트 사용 ❌ 사용 불가 ✅ 서버 컴포넌트 내에서 사용 가능
Middleware 활용 제한적 ✅ 쉽게 적용 가능
Vercel Serverless 최적화 지원됨 ✅ 더 최적화됨

📌 Next.js 15에서는 App Router 기반(app/api/)의 API Routes 사용이 권장됨!


2. API Routes 기본 사용법

1) Next.js 15에서 API Routes 생성하기 (app/api/hello/route.ts)

export async function GET() {
  return new Response(JSON.stringify({ message: "Hello, Next.js API!" }), {
    headers: { "Content-Type": "application/json" },
    status: 200,
  });
}

📌 이제 http://localhost:3000/api/hello로 GET 요청을 보내면 JSON 응답이 반환됨!

2) Next.js API 호출 및 사용 (클라이언트에서 fetch 사용)

async function fetchData() {
  const res = await fetch("/api/hello");
  const data = await res.json();
  console.log(data.message); // "Hello, Next.js API!"
}

fetchData();

📌 이제 클라이언트에서도 API를 쉽게 호출하여 사용할 수 있음!

3) POST 요청 처리하기 (app/api/contact/route.ts)

export async function POST(req: Request) {
  const body = await req.json();
  return new Response(JSON.stringify({ success: true, data: body }), {
    headers: { "Content-Type": "application/json" },
    status: 201,
  });
}

📌 POST 요청 시 데이터를 JSON으로 받아서 처리 가능!

4) 클라이언트에서 API 요청 보내기 (app/contact/page.tsx)

async function submitForm(formData: { name: string; email: string }) {
  const res = await fetch("/api/contact", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(formData),
  });

  const data = await res.json();
  console.log(data); // { success: true, data: { name: "John", email: "john@example.com" } }
}

📌 이제 클라이언트에서 fetch를 이용해 데이터를 서버로 전송 가능!


✅ 여기까지 Next.js 15에서 API Routes를 설정하고 기본적으로 GET/POST 요청을 처리하는 방법을 배웠습니다!
👉 "그렇다면, Next.js 15 API Routes에서 데이터베이스 연동은 어떻게 할까?"
2부에서 API Routes를 활용하여 데이터베이스와 연동하는 방법을 배워봅시다!

반응형

 

2. 상세 주제 정리

 

1. API Routes에서 데이터베이스와 연동하는 방법

Next.js 15에서는 Prisma, MongoDB, PostgreSQL, MySQL 등 다양한 데이터베이스와 쉽게 연동 가능하다.
여기서는 Prisma를 활용하여 PostgreSQL과 연동하는 예제를 다룰 것이다.

1) Prisma와 PostgreSQL 설정하기

$ npm install @prisma/client
$ npx prisma init

📌 Prisma를 설치하고, prisma/schema.prisma 파일이 생성됨!

2) Prisma 모델 설정 (prisma/schema.prisma)

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Contact {
  id    String @id @default(uuid())
  name  String
  email String
}

📌 데이터베이스 테이블을 정의하고, Contact 모델을 생성!

3) 데이터베이스 마이그레이션 실행

$ npx prisma migrate dev --name init

📌 Prisma 마이그레이션을 실행하여 데이터베이스 스키마를 생성!


2. Next.js 15 API Routes에서 데이터 삽입 및 조회

1) 데이터 삽입 API (app/api/contact/route.ts)

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function POST(req: Request) {
  const body = await req.json();
  const contact = await prisma.contact.create({
    data: { name: body.name, email: body.email },
  });

  return new Response(JSON.stringify({ success: true, contact }), {
    headers: { "Content-Type": "application/json" },
    status: 201,
  });
}

📌 POST 요청을 받아 데이터베이스에 데이터를 삽입하는 API!

2) 데이터 조회 API (app/api/contact/route.ts)

export async function GET() {
  const contacts = await prisma.contact.findMany();
  return new Response(JSON.stringify(contacts), {
    headers: { "Content-Type": "application/json" },
    status: 200,
  });
}

📌 GET 요청을 받아 데이터베이스에서 데이터를 조회하는 API!

3) 클라이언트에서 데이터 가져오기 (app/contact/page.tsx)

async function fetchContacts() {
  const res = await fetch("/api/contact");
  const data = await res.json();
  console.log(data); // [{ id: "uuid", name: "John", email: "john@example.com" }]
}

fetchContacts();

📌 이제 API를 통해 데이터베이스의 정보를 가져올 수 있음!


✅ 여기까지 Next.js 15 API Routes를 활용하여 백엔드 없이 서버 기능을 구현하고 데이터베이스와 연동하는 방법을 배웠습니다!
👉 "그렇다면, Next.js 15에서는 서버 컴포넌트와 데이터 패칭을 어떻게 할까?"
다음 회차에서 Next.js 15의 데이터 패칭 방식(SSR, SSG, ISR, RSC)을 배워봅시다!

반응형