{"id":"b1f38efa-2792-45d8-a97f-d59ccd264904","shortId":"TWgREh","kind":"skill","title":"Apollo Server","tagline":"Skills skill by Apollographql","description":"# Apollo Server 5.x Guide\n\nApollo 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.\n\n## Quick Start\n\n### Step 1: Install\n\n```bash\nnpm install @apollo/server graphql\n```\n\nFor Express integration:\n\n```bash\nnpm install @apollo/server @as-integrations/express5 express graphql cors\n```\n\n### Step 2: Define Schema\n\n```typescript\nconst typeDefs = `#graphql\n  type Book {\n    title: String\n    author: String\n  }\n\n  type Query {\n    books: [Book]\n  }\n`;\n```\n\n### Step 3: Write Resolvers\n\n```typescript\nconst resolvers = {\n  Query: {\n    books: () => [\n      { title: \"The Great Gatsby\", author: \"F. Scott Fitzgerald\" },\n      { title: \"1984\", author: \"George Orwell\" },\n    ],\n  },\n};\n```\n\n### Step 4: Start Server\n\n**Standalone (Recommended for prototyping):**\n\nThe 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.\n\n```typescript\nimport { ApolloServer } from \"@apollo/server\";\nimport { startStandaloneServer } from \"@apollo/server/standalone\";\n\nconst server = new ApolloServer({ typeDefs, resolvers });\n\nconst { url } = await startStandaloneServer(server, {\n  listen: { port: 4000 },\n});\n\nconsole.log(`Server ready at ${url}`);\n```\n\n**Express:**\n\n```typescript\nimport { ApolloServer } from \"@apollo/server\";\nimport { expressMiddleware } from \"@as-integrations/express5\";\nimport { ApolloServerPluginDrainHttpServer } from \"@apollo/server/plugin/drainHttpServer\";\nimport express from \"express\";\nimport http from \"http\";\nimport cors from \"cors\";\n\nconst app = express();\nconst httpServer = http.createServer(app);\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],\n});\n\nawait server.start();\n\napp.use(\n  \"/graphql\",\n  cors(),\n  express.json(),\n  expressMiddleware(server, {\n    context: async ({ req }) => ({ token: req.headers.authorization }),\n  }),\n);\n\nawait new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));\nconsole.log(\"Server ready at http://localhost:4000/graphql\");\n```\n\n## Schema Definition\n\n### Scalar Types\n\n- `Int` - 32-bit integer\n- `Float` - Double-precision floating-point\n- `String` - UTF-8 string\n- `Boolean` - true/false\n- `ID` - Unique identifier (serialized as String)\n\n### Type Definitions\n\n```graphql\ntype User {\n  id: ID!\n  name: String!\n  email: String\n  posts: [Post!]!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  content: String\n  author: User!\n}\n\ninput CreatePostInput {\n  title: String!\n  content: String\n}\n\ntype Query {\n  user(id: ID!): User\n  users: [User!]!\n}\n\ntype Mutation {\n  createPost(input: CreatePostInput!): Post!\n}\n```\n\n### Enums and Interfaces\n\n```graphql\nenum Status {\n  DRAFT\n  PUBLISHED\n  ARCHIVED\n}\n\ninterface Node {\n  id: ID!\n}\n\ntype Article implements Node {\n  id: ID!\n  title: String!\n}\n```\n\n## Resolvers Overview\n\nResolvers follow the signature: `(parent, args, contextValue, info)`\n\n- **parent**: Result from parent resolver (root resolvers receive undefined)\n- **args**: Arguments passed to the field\n- **contextValue**: Shared context object (auth, dataSources, etc.)\n- **info**: Field-specific info and schema details (rarely used)\n\n```typescript\nconst resolvers = {\n  Query: {\n    user: async (_, { id }, { dataSources }) => {\n      return dataSources.usersAPI.getUser(id);\n    },\n  },\n  User: {\n    posts: async (parent, _, { dataSources }) => {\n      return dataSources.postsAPI.getPostsByAuthor(parent.id);\n    },\n  },\n  Mutation: {\n    createPost: async (_, { input }, { dataSources, user }) => {\n      if (!user) throw new GraphQLError(\"Not authenticated\");\n      return dataSources.postsAPI.create({ ...input, authorId: user.id });\n    },\n  },\n};\n```\n\n## Context Setup\n\nContext is created per-request and passed to all resolvers.\n\n```typescript\ninterface MyContext {\n  token?: string;\n  user?: User;\n  dataSources: {\n    usersAPI: UsersDataSource;\n    postsAPI: PostsDataSource;\n  };\n}\n\nconst server = new ApolloServer<MyContext>({\n  typeDefs,\n  resolvers,\n});\n\n// Standalone\nconst { url } = await startStandaloneServer(server, {\n  context: async ({ req }) => ({\n    token: req.headers.authorization || \"\",\n    user: await getUser(req.headers.authorization || \"\"),\n    dataSources: {\n      usersAPI: new UsersDataSource(),\n      postsAPI: new PostsDataSource(),\n    },\n  }),\n});\n\n// Express middleware\nexpressMiddleware(server, {\n  context: async ({ req, res }) => ({\n    token: req.headers.authorization,\n    user: await getUser(req.headers.authorization),\n    dataSources: {\n      usersAPI: new UsersDataSource(),\n      postsAPI: new PostsDataSource(),\n    },\n  }),\n});\n```\n\n## Reference Files\n\nDetailed documentation for specific topics:\n\n- [Resolvers](references/resolvers.md) - Resolver patterns and best practices\n- [Context and Auth](references/context-and-auth.md) - Authentication and authorization\n- [Plugins](references/plugins.md) - Server and request lifecycle hooks\n- [Data Sources](references/data-sources.md) - RESTDataSource and DataLoader\n- [Error Handling](references/error-handling.md) - GraphQLError and error formatting\n- [Troubleshooting](references/troubleshooting.md) - Common issues and solutions\n\n## Key Rules\n\n### Schema Design\n\n- Use **!** (non-null) for fields that always have values\n- Prefer input types for mutations over inline arguments\n- Use interfaces for polymorphic types\n- Keep schema descriptions for documentation\n\n### Resolver Best Practices\n\n- Keep resolvers thin - delegate to services/data sources\n- Always handle errors explicitly\n- Use DataLoader for batching related queries\n- Return partial data when possible (GraphQL's strength)\n\n### Performance\n\n- Use `@defer` and `@stream` for large responses\n- Implement DataLoader to solve N+1 queries\n- Consider persisted queries for production\n- Use caching headers and CDN where appropriate\n\n## Ground Rules\n\n- ALWAYS use Apollo Server 5.x patterns (not v4 or earlier)\n- ALWAYS type your context with TypeScript generics\n- ALWAYS use `GraphQLError` from `graphql` package for errors\n- NEVER expose stack traces in production errors\n- PREFER `startStandaloneServer` for prototyping only\n- USE an integration with a server framework like Express, Koa, Fastify, Next, etc. for production apps\n- IMPLEMENT authentication in context, authorization in resolvers","tags":["apollo","server","skills","apollographql"],"capabilities":["skill","source-apollographql","category-skills"],"categories":["skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/apollographql/skills/apollo-server","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"install_from":"skills.sh"}},"qualityScore":"0.300","qualityRationale":"deterministic score 0.30 from registry signals: · indexed on skills.sh · published under apollographql/skills","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill:v1","enrichmentVersion":1,"enrichedAt":"2026-04-22T22:40:29.456Z","embedding":null,"createdAt":"2026-04-18T20:33:43.758Z","updatedAt":"2026-04-22T22:40:29.456Z","lastSeenAt":"2026-04-22T22:40:29.456Z","tsv":"'+1':623 '-8':276 '/express5':65,199 '/graphql':235 '1':48 '1984':105 '2':70 '3':88 '32':264 '4':110 '4000':181,251 '4000/graphql':258 '5':9,29,643 'agnost':33 'alway':561,592,639,650,657 'apollo':1,7,12,27,131,641 'apollo/server':53,61,163,192 'apollo/server/plugin/drainhttpserver':203 'apollo/server/standalone':167 'apollographql':6 'apolloserv':161,171,190,226,457 'apolloserverplugindrainhttpserv':201,230 'app':217,222,692 'app.use':234 'appropri':636 'archiv':337 'arg':357,369 'argument':370,571 'articl':343 'as-integr':62,196 'async':241,397,405,413,467,487 'auth':379,519 'authent':423,521,694 'author':81,100,106,307,523,697 'authorid':427 'await':176,232,245,463,472,493 'bash':50,58 'batch':599 'best':515,583 'bit':265 'book':78,85,86,95 'boolean':278 'cach':631 'category-skills' 'cdn':634 'common':546 'consid':625 'console.log':182,253 'const':74,92,168,174,216,219,223,393,454,461 'content':305,313 'context':240,377,429,431,466,486,517,653,696 'contextvalu':358,375 'cor':68,213,215,236 'creat':433 'createpost':325,412 'createpostinput':310,327 'data':531,604 'dataload':536,597,619 'datasourc':380,399,407,415,449,475,496 'datasources.postsapi.create':425 'datasources.postsapi.getpostsbyauthor':409 'datasources.usersapi.getuser':401 'defer':612 'defin':71 'definit':260,287 'deleg':588 'descript':579 'design':553 'detail':389,505 'document':506,581 'doubl':269 'double-precis':268 'draft':335 'earlier':649 'email':295 'enum':329,333 'environ':44 'error':537,542,594,664,671 'etc':381,689 'explicit':595 'expos':666 'express':40,56,66,143,187,205,207,218,482,685 'express.json':237 'expressmiddlewar':194,238,484 'f':101 'fastifi':41,146,687 'featur':138 'field':374,384,559 'field-specif':383 'file':504 'fitzgerald':103 'float':267,272 'floating-point':271 'follow':353 'format':543 'framework':32,140,155,683 'framework-agnost':31 'fulli':137 'fully-featur':136 'gatsbi':99 'generic':656 'georg':107 'getus':473,494 'graphql':19,25,54,67,76,288,332,607,661 'graphqlerror':421,540,659 'great':98,121 'ground':637 'guid':11 'handl':538,593 'header':632 'hook':530 'http':209,211 'http.createserver':221 'httpserver':220,231 'httpserver.listen':249 'id':280,291,292,301,302,318,319,340,341,346,347,398,402 'identifi':282 'implement':344,618,693 'import':160,164,189,193,200,204,208,212 'info':359,382,386 'inlin':570 'input':309,326,414,426,565 'instal':49,52,60 'int':263 'integ':266 'integr':38,57,64,130,198,679 'interfac':331,338,443,573 'issu':547 'keep':577,585 'key':550 'koa':144,686 'larg':616 'later':156 'lifecycl':529 'like':684 'listen':179 'localhost':257 'middlewar':483 'mutat':324,411,568 'mycontext':444 'n':622 'name':293 'never':665 'new':170,225,246,420,456,477,480,498,501 'next':688 'node':339,345 'non':556 'non-nul':555 'npm':51,59 'null':557 'object':378 'open':17 'open-sourc':16 'orwel':108 'overview':351 'packag':662 'parent':356,360,363,406 'parent.id':410 'partial':603 'pass':371,438 'pattern':513,645 'per':435 'per-request':434 'perform':610 'persist':626 'plugin':229,524 'point':273 'polymorph':575 'port':180,250 'possibl':606 'post':297,298,300,328,404 'postsapi':452,479,500 'postsdatasourc':453,481,502 'practic':516,584 'precis':270 'prefer':564,672 'product':126,629,670,691 'promis':247 'prototyp':116,123,675 'publish':336 'queri':84,94,316,395,601,624,627 'quick':45 'rare':390 'readi':184,255 'receiv':367 'recommend':114,129 'refer':503 'references/context-and-auth.md':520 'references/data-sources.md':533 'references/error-handling.md':539 'references/plugins.md':525 'references/resolvers.md':511 'references/troubleshooting.md':545 'relat':600 'req':242,468,488 'req.headers.authorization':244,470,474,491,495 'request':436,528 'res':489 'resolv':90,93,173,228,248,252,350,352,364,366,394,441,459,510,512,582,586,699 'respons':617 'restdatasourc':534 'result':361 'return':400,408,424,602 'root':365 'rule':551,638 'run':35 'scalar':261 'schema':26,72,259,388,552,578 'scott':102 'serial':283 'server':2,8,13,20,28,112,119,132,151,169,178,183,224,239,254,455,465,485,526,642,682 'server.start':233 'serverless':43 'servic':127 'services/data':590 'setup':430 'share':376 'signatur':355 'skill':3,4 'solut':549 'solv':621 'sourc':18,532,591 'source-apollographql' 'specif':385,508 'stack':667 'standalon':36,113,118,150,460 'start':46,111 'startstandaloneserv':165,177,464,673 'status':334 'step':47,69,87,109 'straightforward':158 'stream':614 'strength':609 'string':80,82,274,277,285,294,296,304,306,312,314,349,446 'swap':147 'thin':587 'throw':419 'titl':79,96,104,303,311,348 'token':243,445,469,490 'topic':509 'trace':668 'troubleshoot':544 'true/false':279 'type':77,83,262,286,289,299,315,323,342,566,576,651 'typedef':75,172,227,458 'typescript':73,91,159,188,392,442,655 'undefin':368 'uniqu':281 'url':175,186,462 'use':391,554,572,596,611,630,640,658,677 'user':290,308,317,320,321,322,396,403,416,418,447,448,471,492 'user.id':428 'usersapi':450,476,497 'usersdatasourc':451,478,499 'utf':275 'v4':647 'valu':563 'web':139,154 'work':22 'write':89 'x':10,644","prices":[{"id":"de85bbce-93bd-49ea-b070-67768e88ef58","listingId":"b1f38efa-2792-45d8-a97f-d59ccd264904","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"apollographql","category":"skills","install_from":"skills.sh"},"createdAt":"2026-04-18T20:33:43.758Z"}],"sources":[{"listingId":"b1f38efa-2792-45d8-a97f-d59ccd264904","source":"github","sourceId":"apollographql/skills/apollo-server","sourceUrl":"https://github.com/apollographql/skills/tree/main/skills/apollo-server","isPrimary":false,"firstSeenAt":"2026-04-18T22:17:25.477Z","lastSeenAt":"2026-04-22T18:57:49.710Z"},{"listingId":"b1f38efa-2792-45d8-a97f-d59ccd264904","source":"skills_sh","sourceId":"apollographql/skills/apollo-server","sourceUrl":"https://skills.sh/apollographql/skills/apollo-server","isPrimary":true,"firstSeenAt":"2026-04-18T20:33:43.758Z","lastSeenAt":"2026-04-22T22:40:29.456Z"}],"details":{"listingId":"b1f38efa-2792-45d8-a97f-d59ccd264904","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"apollographql","slug":"apollo-server","source":"skills_sh","category":"skills","skills_sh_url":"https://skills.sh/apollographql/skills/apollo-server"},"updatedAt":"2026-04-22T22:40:29.456Z"}}