apollo-server

작성자: apollographql

Apollo Server 5.x를 활용한 GraphQL 서버 구축 완전 가이드. 스키마 정의, 리졸버, 컨텍스트 설정, TypeScript 지원을 통한 오류 처리를 다룹니다. 프로토타이핑을 위한 독립 실행 모드와 Express, Fastify, Koa, 서버리스 환경과의 통합을 지원합니다. 리졸버 패턴, 인증/권한 부여, 플러그인, N+1 문제 방지를 위한 DataLoader, 성능 최적화 기법을 포함합니다. 데이터 소스, 오류...에 대한 참조 문서를 제공합니다.

npx skills add https://github.com/apollographql/skills --skill apollo-server

Apollo Server 5.x Guide

Apollo Server is an open-source GraphQL server that works with any GraphQL schema. Apollo Server 5 is framework-agnostic and runs standalone or integrates with Express, Fastify, and serverless environments.

Quick Start

Step 1: Install

npm install @apollo/server graphql

For Express integration:

npm install @apollo/server @as-integrations/express5 express graphql cors

Step 2: Define Schema

const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

Step 3: Write Resolvers

const resolvers = {
  Query: {
    books: () => [
      { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
      { title: "1984", author: "George Orwell" },
    ],
  },
};

Step 4: Start Server

Standalone (Recommended for prototyping):

The standalone server is great for prototyping, but for production services, we recommend integrating Apollo Server with a more fully-featured web framework such as Express, Koa, or Fastify. Swapping from the standalone server to a web framework later is straightforward.

import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

const server = new ApolloServer({ typeDefs, resolvers });

const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
});

console.log(`Server ready at ${url}`);

Express:

import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@as-integrations/express5";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import express from "express";
import http from "http";
import cors from "cors";

const app = express();
const httpServer = http.createServer(app);

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

app.use(
  "/graphql",
  cors(),
  express.json(),
  expressMiddleware(server, {
    context: async ({ req }) => ({ token: req.headers.authorization }),
  }),
);

await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log("Server ready at http://localhost:4000/graphql");

Schema Definition

Scalar Types

  • Int - 32-bit integer
  • Float - Double-precision floating-point
  • String - UTF-8 string
  • Boolean - true/false
  • ID - Unique identifier (serialized as String)

Type Definitions

type User {
  id: ID!
  name: String!
  email: String
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  content: String
  author: User!
}

input CreatePostInput {
  title: String!
  content: String
}

type Query {
  user(id: ID!): User
  users: [User!]!
}

type Mutation {
  createPost(input: CreatePostInput!): Post!
}

Enums and Interfaces

enum Status {
  DRAFT
  PUBLISHED
  ARCHIVED
}

interface Node {
  id: ID!
}

type Article implements Node {
  id: ID!
  title: String!
}

Resolvers Overview

Resolvers follow the signature: (parent, args, contextValue, info)

  • parent: Result from parent resolver (root resolvers receive undefined)
  • args: Arguments passed to the field
  • contextValue: Shared context object (auth, dataSources, etc.)
  • info: Field-specific info and schema details (rarely used)
const resolvers = {
  Query: {
    user: async (_, { id }, { dataSources }) => {
      return dataSources.usersAPI.getUser(id);
    },
  },
  User: {
    posts: async (parent, _, { dataSources }) => {
      return dataSources.postsAPI.getPostsByAuthor(parent.id);
    },
  },
  Mutation: {
    createPost: async (_, { input }, { dataSources, user }) => {
      if (!user) throw new GraphQLError("Not authenticated");
      return dataSources.postsAPI.create({ ...input, authorId: user.id });
    },
  },
};

Context Setup

Context is created per-request and passed to all resolvers.

interface MyContext {
  token?: string;
  user?: User;
  dataSources: {
    usersAPI: UsersDataSource;
    postsAPI: PostsDataSource;
  };
}

const server = new ApolloServer<MyContext>({
  typeDefs,
  resolvers,
});

// Standalone
const { url } = await startStandaloneServer(server, {
  context: async ({ req }) => ({
    token: req.headers.authorization || "",
    user: await getUser(req.headers.authorization || ""),
    dataSources: {
      usersAPI: new UsersDataSource(),
      postsAPI: new PostsDataSource(),
    },
  }),
});

// Express middleware
expressMiddleware(server, {
  context: async ({ req, res }) => ({
    token: req.headers.authorization,
    user: await getUser(req.headers.authorization),
    dataSources: {
      usersAPI: new UsersDataSource(),
      postsAPI: new PostsDataSource(),
    },
  }),
});

Reference Files

Detailed documentation for specific topics:

Key Rules

Schema Design

  • Use ! (non-null) for fields that always have values
  • Prefer input types for mutations over inline arguments
  • Use interfaces for polymorphic types
  • Keep schema descriptions for documentation

Resolver Best Practices

  • Keep resolvers thin - delegate to services/data sources
  • Always handle errors explicitly
  • Use DataLoader for batching related queries
  • Return partial data when possible (GraphQL's strength)

Performance

  • Use @defer and @stream for large responses
  • Implement DataLoader to solve N+1 queries
  • Consider persisted queries for production
  • Use caching headers and CDN where appropriate

Ground Rules

  • ALWAYS use Apollo Server 5.x patterns (not v4 or earlier)
  • ALWAYS type your context with TypeScript generics
  • ALWAYS use GraphQLError from graphql package for errors
  • NEVER expose stack traces in production errors
  • PREFER startStandaloneServer for prototyping only
  • USE an integration with a server framework like Express, Koa, Fastify, Next, etc. for production apps
  • IMPLEMENT authentication in context, authorization in resolvers

apollographql의 다른 스킬

apollo-client
apollographql
Apollo Client는 로컬 및 원격 데이터를 GraphQL로 관리할 수 있게 해주는 JavaScript용 종합 상태 관리 라이브러리입니다. 버전 4.x는 개선된 캐싱, 더 나은 TypeScript 지원, React 19 호환성을 제공합니다.
official
apollo-client
apollographql
Apollo Client 4.x를 사용하여 React 애플리케이션을 구축하기 위한 종합 가이드로, 쿼리, 뮤테이션, 캐싱 및 상태 관리를 다룹니다. 여러 React 프레임워크 및 설정을 지원합니다: 클라이언트 측 앱(Vite, CRA), React Server Components를 사용하는 Next.js App Router, 스트리밍 SSR을 지원하는 React Router 7, TanStack Start. 쿼리(useQuery, useLazyQuery), 뮤테이션(useMutation)을 위한 훅과 최신 React 18+ 및 19를 위한 Suspense 기반 패턴(useSuspenseQuery, useBackgroundQuery)을 포함합니다.
official
apollo-connectors
apollographql
REST API를 @source 및 @connect 지시문을 사용하여 GraphQL 슈퍼그래프에 통합합니다. 구조화된 5단계 프로세스를 제공합니다: API 구조 조사, 지시문으로 스키마 구현, rover supergraph compose를 통한 검증, 커넥터 실행, 테스트 커버리지. 헤더, 본문 페이로드, N+1 패턴을 위한 배칭, $env를 통한 환경 변수 주입을 포함한 요청 구성을 지원합니다. 필드 선택, 별칭, 중첩 데이터를 위한 하위 선택, 엔티티...를 포함한 응답 매핑을 처리합니다.
official
apollo-federation
apollographql
Apollo Federation은 여러 GraphQL API(서브그래프)를 하나의 통합된 슈퍼그래프로 구성할 수 있게 해줍니다.
official
apollo-ios
apollographql
Apollo iOS는 Apple 플랫폼을 위한 강력한 타입의 GraphQL 클라이언트입니다. GraphQL 작업과 스키마에서 Swift 타입을 생성하며, async/await 클라이언트, 정규화된 캐시(인메모리 또는 SQLite 기반), 쿼리, 뮤테이션 및 멀티파트 구독을 처리하는 플러그형 인터셉터 기반 HTTP 전송, 그리고 모든 작업 유형을 전달할 수 있는 선택적 WebSocket 전송(graphql-transport-ws)을 제공합니다.
official
apollo-kotlin
apollographql
Apollo Kotlin은 GraphQL 연산과 스키마에서 Kotlin 모델을 생성하는 강력한 타입의 GraphQL 클라이언트로, Android, JVM 및 Kotlin Multiplatform 프로젝트에서 사용할 수 있습니다.
official
apollo-mcp-server
apollographql
AI 에이전트를 GraphQL API에 연결하여 Model Context Protocol을 통해 내장된 인트로스펙션 및 작업 도구를 제공합니다. GraphQL 작업을 MCP 도구로 노출하며, 로컬 파일, GraphOS Studio 컬렉션, 지속적 쿼리 매니페스트의 세 가지 작업 소스를 지원합니다. 스키마 탐색 및 임시 쿼리 테스트를 위한 네 가지 인트로스펙션 도구(introspect, search, validate, execute)를 제공하며, 축약 표기법을 사용한 미니피케이션 모드로 토큰 사용량을 줄입니다. 정적 헤더를 통한 구성 가능한 인증,...
official
apollo-router
apollographql
Apollo Router는 Apollo Federation 2 슈퍼그래프를 실행하기 위해 Rust로 작성된 고성능 그래프 라우터입니다. 서브그래프 앞에 위치하여 쿼리 계획, 실행 및 응답 구성을 처리합니다.
official