apollo-server

Vollständiger Leitfaden zum Erstellen von GraphQL-Servern mit Apollo Server 5.x in verschiedenen Frameworks. Behandelt Schema-Definition, Resolver, Kontext-Einrichtung und Fehlerbehandlung mit TypeScript-Unterstützung. Unterstützt Standalone-Modus für Prototyping sowie Integrationen mit Express, Fastify, Koa und serverlosen Umgebungen. Enthält Resolver-Muster, Authentifizierung/Autorisierung, Plugins, DataLoader zur N+1-Vermeidung und Techniken zur Leistungsoptimierung. Bietet Referenzdokumentation für Datenquellen, Fehler...

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

Mehr Skills von apollographql

apollo-federation
apollographql
Apollo Federation ermöglicht das Zusammenführen mehrerer GraphQL-APIs (Subgraphen) zu einem einheitlichen Supergraphen.
apollo-ios
apollographql
Apollo iOS ist ein stark typisierter GraphQL-Client für Apple-Plattformen. Er generiert Swift-Typen aus Ihren GraphQL-Operationen und Ihrem Schema und enthält einen Async/Await-Client, einen normalisierten Cache (im Arbeitsspeicher oder SQLite-gestützt), einen steckbaren, auf Interceptoren basierenden HTTP-Transport, der Abfragen, Mutationen und Multipart-Abonnements verarbeitet, sowie einen optionalen WebSocket-Transport (graphql-transport-ws), der jeden Operationstyp übertragen kann.
apollo-router
apollographql
Apollo Router ist ein leistungsstarker Graph-Router, der in Rust geschrieben wurde und für den Betrieb von Apollo Federation 2-Supergraphen entwickelt wurde. Er sitzt vor Ihren Subgraphen und übernimmt die Abfrageplanung, -ausführung und Antwortkomposition.
apollo-router-plugin-creator
apollographql
Erstelle native Rust-Plugins für Apollo Router.
graphql-operations
apollographql
Leitfaden für Best Practices zum Schreiben effizienter, typsicherer GraphQL-Operationen und deren Organisation mit Fragmenten. Behandelt Queries, Mutationen, Subscriptions und Fragmente mit Namenskonventionen, Variablensyntax und Direktivenverwendung. Betont Kernprinzipien: nur benötigte Felder anfordern, alle Operationen benennen, Variablen statt hartcodierter Werte verwenden und ID-Felder für die Cache-Fähigkeit einfügen. Empfiehlt, Fragmente mit Komponenten zu kollokieren und @include-/@skip-Direktiven für bedingte Felder zu nutzen...
graphql-schema
apollographql
We need to translate the given English text into German. The text is a description of a guide for GraphQL schema design. We must preserve the name "graphql-schema" but it's not in the text, so we don't include it. We must not add any extra commentary, labels, etc. Just translate the text. The text: "Industry best practices guide for designing intuitive, performant, and maintainable GraphQL schemas. Covers core design principles including client-centric type organization, explicit nullability patterns, and backwards-compatible evolution strategies Provides reference documentation on types, naming conventions, cursor-based pagination, error modeling, and security considerations Includes practical patterns for interfaces, unions, input types, mutations, and ID strategies with code examples" Note: There is a missing period after "strategies" and before "Provides". We'll treat it as two sentences. Also "code examples" at the end. Translation to German: "Leitfaden für Branchen-Best Practices zur Gestaltung intuitiver, leistungsfähiger und wartbarer GraphQL-S
rover
apollographql
We need to translate the given English text into German, preserving the name "rover" and any technical terms. The text describes the Apollo Rover CLI. We must not add any extra commentary or labels. The translation should be accurate and natural in German. Let's break down the text: "Apollo Rover CLI for managing GraphQL schemas, federation, and local supergraph development. Publish, fetch, and validate subgraph schemas; compose federated supergraphs locally or via GraphOS Includes schema checking (pre-deploy validation), linting, and introspection from running servers rover dev command starts a local Router with automatic schema composition for development workflows Supports CI/CD patterns with check-before-publish validation and JSON output for scripting Requires..." We need to translate this into German. Keep "rover" as is. Also "GraphQL", "federation", "supergraph", "subgraph", "GraphOS", "Router", "CI/CD", "JSON" are technical terms that should remain in English or be commonly used in German tech contexts. Usually, these are kept as is
rust-best-practices
apollographql
We need to translate the given English text into German, preserving the name "rust-best-practices" if it appears. The text is a description of an agent skill. The instruction says: "Do not include the name unless it appears in the source text." The name "rust-best-practices" does not appear in the provided <text> block. So we should not add it. Also, preserve product names, protocol names, URLs, numbers, technical terms. So "Apollo GraphQL", "clippy", "thiserror", "anyhow", "Result", etc. should remain as is or translated? Technical terms like "clippy linting" might be kept as "Clippy-Linting" or similar. But the instruction says "preserve product names, protocol names, URLs, numbers, and technical terms." So we keep them in original form. However, we are translating to German, so we need to produce a natural German translation. For example, "Idiomatic Rust coding standards" -> "Idiomatische Rust-Codierungsstand