IT Developer/Next.js

Next.js 기초 <16. Next.js 15에서 GraphQL과 Apollo를 활용한 데이터 관리>

TEMA_ 2025. 3. 19. 19:52
반응형

넥스트 Next.js

16. Next.js 15에서 GraphQL과 Apollo를 활용한 데이터 관리 

 

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

Next.js 기초 강좌입니다.

 

강좌의 경우 

1. 주제 간단 정리

2. 상세 주제 정리

으로 이루어져 있습니다.

 

넥스트 Next.js

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


 

1. 주제 간단 정리

 

1. Next.js 15에서 GraphQL을 사용하는 이유

GraphQL은 REST API보다 유연하고 효율적인 데이터 쿼리 방식을 제공한다.
Next.js 15에서는 Apollo Client 또는 urql 같은 GraphQL 라이브러리를 활용하여 데이터를 관리할 수 있다.

📌 Next.js 15에서 GraphQL을 사용하는 주요 이유
필요한 데이터만 요청 가능 → 불필요한 데이터 로딩 방지
다중 요청을 하나의 쿼리로 처리 가능 → API 호출 횟수 감소
백엔드의 유연한 스키마 적용 가능 → 다양한 클라이언트 지원

GraphQL과 REST API 비교

특징GraphQLREST API

데이터 요청 방식 필요한 데이터만 선택 가능 정해진 엔드포인트에서 제공하는 데이터만 가능
다중 요청 하나의 요청으로 여러 데이터 가능 여러 개의 API 요청 필요
유연성 클라이언트가 데이터 구조 결정 서버에서 미리 정의된 응답 구조 제공
오버페칭(Overfetching) 문제 ❌ 불필요한 데이터 로드 없음 ✅ 필요한 데이터 외 추가 정보 포함 가능

📌 Next.js 15에서는 "GraphQL + Apollo Client" 조합이 가장 많이 사용됨!


2. Next.js 15에서 GraphQL 서버 구축하기 (Apollo Server 사용)

1) Apollo Server 설치

$ npm install @apollo/server graphql

📌 GraphQL 서버를 실행하기 위한 Apollo Server 설치!

2) Apollo Server 설정 (app/api/graphql/route.ts)

import { ApolloServer } from "@apollo/server";
import { startServerAndCreateNextHandler } from "@as-integrations/next";

const typeDefs = `
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => "🚀 Next.js 15 + GraphQL!",
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
export const GET = startServerAndCreateNextHandler(server);
export const POST = startServerAndCreateNextHandler(server);

📌 GraphQL 서버가 /api/graphql 엔드포인트에서 실행되도록 설정!

3) GraphQL Playground 테스트 (http://localhost:3000/api/graphql)

query {
  hello
}

📌 GraphQL Playground에서 hello 필드를 요청하면 🚀 Next.js 15 + GraphQL! 응답을 받을 수 있음!


✅ 여기까지 Next.js 15에서 기본적인 GraphQL 서버를 구축하는 방법을 배웠습니다!
👉 "그렇다면, Next.js 15에서 Apollo Client를 활용하여 데이터를 가져오려면?"
2부에서 Apollo Client를 활용한 데이터 관리 방법을 배워봅시다!

반응형

 

2. 상세 주제 정리

 

1. Next.js 15에서 Apollo Client 설정하기

1) Apollo Client 설치

$ npm install @apollo/client graphql

📌 Apollo Client를 설치하여 클라이언트에서 GraphQL 데이터를 쉽게 가져올 수 있음!

2) Apollo Client 설정 파일 (lib/apollo-client.ts)

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: "/api/graphql",
  cache: new InMemoryCache(),
});

export default client;

📌 Apollo Client가 Next.js 15에서 사용할 GraphQL 서버 URI를 설정!

3) Apollo Provider 설정 (app/providers.tsx)

"use client";
import { ApolloProvider } from "@apollo/client";
import client from "@/lib/apollo-client";

export function Providers({ children }: { children: React.ReactNode }) {
  return <ApolloProvider client={client}>{children}</ApolloProvider>;
}

📌 Apollo Provider를 사용하여 모든 페이지에서 GraphQL 데이터를 사용할 수 있도록 설정!

4) layout.tsx에서 Provider 적용 (app/layout.tsx)

import { Providers } from "@/providers";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="ko">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

📌 이제 Next.js 15의 모든 컴포넌트에서 Apollo Client를 사용할 수 있음!


2. Next.js 15에서 Apollo Client를 활용하여 데이터 가져오기

1) GraphQL 데이터 가져오기 (app/components/GraphQLQuery.tsx)

"use client";
import { useQuery, gql } from "@apollo/client";

const GET_GREETING = gql`
  query {
    hello
  }
`;

export default function GraphQLQuery() {
  const { data, loading, error } = useQuery(GET_GREETING);

  if (loading) return <p>로딩 중...</p>;
  if (error) return <p>에러 발생: {error.message}</p>;

  return <h2>{data.hello}</h2>;
}

📌 GraphQL에서 데이터를 가져와 화면에 표시 가능!

2) 데이터 추가 (Mutation 활용) (app/components/GraphQLMutation.tsx)

"use client";
import { useState } from "react";
import { useMutation, gql } from "@apollo/client";

const ADD_MESSAGE = gql`
  mutation AddMessage($text: String!) {
    addMessage(text: $text) {
      id
      text
    }
  }
`;

export default function GraphQLMutation() {
  const [text, setText] = useState("");
  const [addMessage] = useMutation(ADD_MESSAGE);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await addMessage({ variables: { text } });
    setText("");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={text} onChange={(e) => setText(e.target.value)} placeholder="메시지 입력" />
      <button type="submit">추가</button>
    </form>
  );
}

📌 GraphQL Mutation을 활용하여 데이터를 추가하고 업데이트 가능!


3. Next.js 15에서 GraphQL Subscriptions (실시간 데이터 스트리밍)

1) WebSocket을 활용한 GraphQL 실시간 데이터 처리 (app/api/graphql/route.ts)

import { ApolloServer } from "@apollo/server";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";

const typeDefs = `
  type Message {
    id: ID!
    text: String!
  }

  type Query {
    messages: [Message!]
  }

  type Mutation {
    addMessage(text: String!): Message
  }

  type Subscription {
    messageAdded: Message!
  }
`;

let messages: { id: string; text: string }[] = [];

const resolvers = {
  Query: {
    messages: () => messages,
  },
  Mutation: {
    addMessage: (_, { text }) => {
      const message = { id: String(messages.length + 1), text };
      messages.push(message);
      return message;
    },
  },
  Subscription: {
    messageAdded: {
      subscribe: (_, __, { pubsub }) => pubsub.asyncIterator(["MESSAGE_ADDED"]),
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
export const GET = startServerAndCreateNextHandler(server);
export const POST = startServerAndCreateNextHandler(server);

 

📌 WebSocket을 활용한 GraphQL Subscriptions을 구현하여 실시간 데이터 업데이트 가능!


여기까지 Next.js 15에서 Apollo Client와 GraphQL을 활용한 데이터 관리 방법을 배웠습니다!
👉 "그렇다면, Next.js 15에서 성능 최적화 및 코드 스플리팅은 어떻게 할까?"
다음 회차에서 Next.js 15에서 성능 최적화 및 코드 스플리팅을 배워봅시다!

 

반응형