← Back to Node.js, page 9

nodejs-0165 · Medium mid

How do you build an Apollo Server API in Node.js: typeDefs, resolvers, context for authentication, error codes and production settings?

Apollo Server takes typeDefs (the schema) and resolvers. The context function runs for each request and is the place to add the authenticated user and per-request helpers such as DataLoader instances. Throw GraphQLError with an extensions.code (UNAUTHENTICATED, FORBIDDEN, BAD_USER_INPUT) for expected errors, hide stack traces and internal messages in production, and turn off introspection and landing pages unless you need them.

Full answer

Pieces

  • new ApolloServer({ typeDefs, resolvers, ...options }). Use @apollo/server with startStandaloneServer for a quick start or expressMiddleware to mount it inside Express with cors and body parsing.
  • Resolvers receive (parent, args, contextValue, info). Keep them thin and call services.
  • Context: created per request. Typical content: the user from a verified token or session, a database handle, and new DataLoader instances (loaders must not be shared between requests, because their cache would leak data between users).

Errors

  • Throw new GraphQLError('message', { extensions: { code: 'UNAUTHENTICATED' } }) for errors that clients should handle. Validation failures get GRAPHQL_VALIDATION_FAILED automatically.
  • Unexpected errors become INTERNAL_SERVER_ERROR. Use formatError to hide internal messages and stack traces in production (includeStacktraceInErrorResponses: false), and log the original error with a request id.
  • Always check authorization in resolvers (or a shared wrapper). The schema alone does not protect fields.

Production settings

  • Introspection is disabled by default when NODE_ENV is production. Do not rely on that only. Set introspection explicitly for public APIs.
  • Limit query depth and cost, request size, and add persisted queries or an allowlist for private clients.
  • Keep the landing page and the sandbox off in production.
  • Plugins add logging, tracing and caching hints. executeOperation lets you test the server without HTTP.
javascript
const { ApolloServer } = require('@apollo/server');
const { GraphQLError } = require('graphql');

const typeDefs = `#graphql
  type Query { me: String!  secret: String!  divide(a: Int!, b: Int!): Int! }
`;
const resolvers = {
  Query: {
    me: (parent, args, { user }) => user ?? 'anonymous',
    secret: (parent, args, { user }) => {
      if (!user) throw new GraphQLError('Please log in', { extensions: { code: 'UNAUTHENTICATED' } });
      return 'the secret for ' + user;
    },
    divide: (parent, { a, b }) => {
      if (b === 0) throw new GraphQLError('b must not be zero', { extensions: { code: 'BAD_USER_INPUT', argument: 'b' } });
      if (a === 13) throw new Error('database password is hunter2');      // an unexpected error
      return Math.floor(a / b);
    },
  },
};

const server = new ApolloServer({
  typeDefs, resolvers,
  includeStacktraceInErrorResponses: false,
  introspection: false,
  formatError: (formatted, error) => (formatted.extensions?.code === 'INTERNAL_SERVER_ERROR' ? { message: 'Internal error', extensions: { code: 'INTERNAL_SERVER_ERROR' } } : formatted),
});

async function run(label, query, user) {
  const response = await server.executeOperation({ query }, { contextValue: { user } });
  const { data, errors } = response.body.singleResult;
  console.log(label.padEnd(24), JSON.stringify({ data, errors: errors?.map((e) => ({ message: e.message, code: e.extensions?.code })) }));
}

(async () => {
  await run('anonymous me', '{ me }');
  await run('secret, anonymous', '{ secret }');
  await run('secret, logged in', '{ secret }', 'asha');
  await run('expected error', '{ divide(a: 1, b: 0) }');
  await run('unexpected error', '{ divide(a: 13, b: 1) }');
  await run('validation error', '{ nothing }');
  await run('introspection', '{ __schema { queryType { name } } }');
})();

executeOperation runs queries without HTTP. The unexpected error is hidden behind a generic message, and introspection is switched off. Install first with npm install @apollo/server graphql (run here with @apollo/server 5.5.4, graphql 16.15.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): anonymous me {"data":{"me":"anonymous"}} secret, anonymous {"data":null,"errors":[{"message":"Please log in","code":"UNAUTHENTICATED"}]} secret, logged in {"data":{"secret":"the secret for asha"}} expected error {"data":null,"errors":[{"message":"b must not be zero","code":"BAD_USER_INPUT"}]} unexpected error {"data":null,"errors":[{"message":"Internal error","code":"INTERNAL_SERVER_ERROR"}]} validation error {"errors":[{"message":"Cannot query field \"nothing\" on type \"Query\".","code":"GRAPHQL_VALIDATION_FAILED"}]} introspection {"errors":[{"message":"GraphQL introspection is not allowed by Apollo Server, but the query contained __schema or __type. To enable introspection, pass introspection: true to ApolloServer in production","code":"GRAPHQL_VALIDATION_FAILED"}]}

Key points

  • ApolloServer takes typeDefs and resolvers.
  • The context function adds the user and per-request loaders.
  • Throw GraphQLError with extensions.code for expected errors.
  • Hide stack traces and set introspection on purpose.
  • executeOperation tests without HTTP.

Common mistakes

  • Sharing a DataLoader or user object between requests.
  • Skipping authorization in resolvers because the route requires login.
  • Returning internal error messages and stack traces.
  • Leaving introspection and the sandbox open on a private API.
  • Throwing plain strings instead of errors with codes.

Follow-ups

  • How do you mount Apollo Server inside an Express app?
  • What does formatError receive?
  • How would you add query depth limiting?

Tips

  • List typeDefs, resolvers, context.
  • Say 'per-request context'.
  • Mention production settings.