or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mderror-handling.mdgraphql-utilities.mdhttp-integration.mdindex.mdplugins.mdserver-core.md
tile.json

configuration.mddocs/

Configuration

Apollo Server Core provides extensive configuration options for GraphQL execution including schema definition, resolvers, context management, and server behavior customization.

Capabilities

Server Configuration

Main configuration interface for Apollo Server providing schema, context, and execution options.

/**
 * Main configuration interface for Apollo Server
 */
interface Config<ContextFunctionParams = any> {
  /** GraphQL schema (either this or typeDefs/resolvers required) */
  schema?: GraphQLSchema;
  
  /** GraphQL type definitions (SDL) */
  typeDefs?: TypeSource;
  
  /** GraphQL resolvers */
  resolvers?: IResolvers;
  
  /** GraphQL schema modules for federation */
  modules?: GraphQLSchemaModule[];
  
  /** Context value or function that produces context */
  context?: Context | ContextFunction<ContextFunctionParams>;
  
  /** Array of plugins to extend server functionality */
  plugins?: PluginDefinition[];
  
  /** Enable GraphQL introspection (default: true in development) */
  introspection?: boolean;
  
  /** Mock configuration for development */
  mocks?: boolean | IMocks;
  
  /** Whether to mock entire schema */
  mockEntireSchema?: boolean;
  
  /** Persisted queries configuration */
  persistedQueries?: PersistedQueryOptions | false;
  
  /** Apollo Federation gateway interface */
  gateway?: GatewayInterface;
  
  /** Apollo Studio configuration */
  apollo?: ApolloConfigInput;
  
  /** CSRF prevention configuration */
  csrfPrevention?: CSRFPreventionOptions | boolean;
  
  /** Cache implementation */
  cache?: KeyValueCache | 'bounded';
  
  /** Custom document store for parsed queries */
  documentStore?: DocumentStore | null;
  
  /** Stop server on termination signals */
  stopOnTerminationSignals?: boolean;
  
  /** Node environment (for default behavior) */
  nodeEnv?: string;
  
  /** Disable GraphQL validation (dangerous) */
  dangerouslyDisableValidation?: boolean;
}

type TypeSource = string | DocumentNode | Array<string | DocumentNode>;

interface IResolvers {
  [key: string]: any;
}

interface IMocks {
  [key: string]: any;
}

Usage Examples:

import { ApolloServerBase, gql } from "apollo-server-core";

// Schema-first approach
const server1 = new ApolloServerBase({
  typeDefs: gql`
    type User {
      id: ID!
      name: String!
      email: String!
    }
    
    type Query {
      users: [User!]!
      user(id: ID!): User
    }
  `,
  resolvers: {
    Query: {
      users: () => getAllUsers(),
      user: (_, { id }) => getUserById(id),
    },
  },
});

// Pre-built schema approach
import { makeExecutableSchema } from '@graphql-tools/schema';

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

const server2 = new ApolloServerBase({
  schema,
});

// With context function
const server3 = new ApolloServerBase({
  typeDefs,
  resolvers,
  context: ({ req }) => ({
    user: req.user,
    dataSources: {
      userAPI: new UserAPI(),
    },
  }),
});

Context Configuration

Context system that provides request-scoped data to GraphQL resolvers.

type Context<T = object> = T;

/**
 * Function that produces context for each request
 * @param context - Input context from integration (req, res, etc.)
 * @returns Context value or Promise resolving to context
 */
type ContextFunction<FunctionParams = any, ProducedContext = object> = (
  context: FunctionParams,
) => ValueOrPromise<Context<ProducedContext>>;

type ValueOrPromise<T> = T | Promise<T>;

Context Examples:

// Static context
const server = new ApolloServerBase({
  typeDefs,
  resolvers,
  context: {
    apiUrl: 'https://api.example.com',
    version: '1.0.0',
  },
});

// Dynamic context function
const server = new ApolloServerBase({
  typeDefs,
  resolvers,
  context: ({ req, res }) => ({
    user: req.user,
    token: req.headers.authorization,
    dataSources: {
      userAPI: new UserAPI(),
      postAPI: new PostAPI(),
    },
  }),
});

// Async context
const server = new ApolloServerBase({
  typeDefs,
  resolvers,
  context: async ({ req }) => {
    const user = await authenticateUser(req.headers.authorization);
    return {
      user,
      permissions: await getUserPermissions(user.id),
    };
  },
});

GraphQL Execution Options

Configuration options that control GraphQL query execution behavior.

interface GraphQLServerOptions<TContext = Record<string, any>, TRootValue = any> {
  /** GraphQL schema */
  schema: GraphQLSchema;
  
  /** Logger implementation */
  logger?: Logger;
  
  /** Error formatting function */
  formatError?: (error: GraphQLError) => GraphQLFormattedError;
  
  /** Root value for execution */
  rootValue?: ((parsedQuery: DocumentNode) => TRootValue) | TRootValue;
  
  /** Context value (set by context function) */
  context?: TContext | (() => never);
  
  /** Additional validation rules */
  validationRules?: Array<(context: ValidationContext) => any>;
  
  /** Custom GraphQL executor */
  executor?: GraphQLExecutor;
  
  /** Response formatting function */
  formatResponse?: (
    response: GraphQLResponse,
    requestContext: GraphQLRequestContext<TContext>
  ) => GraphQLResponse | null;
  
  /** Custom field resolver */
  fieldResolver?: GraphQLFieldResolver<any, TContext>;
  
  /** Enable debug mode */
  debug?: boolean;
  
  /** Data sources factory function */
  dataSources?: () => DataSources<TContext>;
  
  /** Cache implementation */
  cache?: KeyValueCache;
  
  /** Persisted queries configuration */
  persistedQueries?: PersistedQueryOptions;
  
  /** Server plugins */
  plugins?: ApolloServerPlugin[];
  
  /** Document store for parsed queries */
  documentStore?: DocumentStore | null;
  
  /** Disable validation (dangerous) */
  dangerouslyDisableValidation?: boolean;
  
  /** GraphQL parsing options */
  parseOptions?: ParseOptions;
  
  /** Node environment */
  nodeEnv?: string;
  
  /** Allow batched HTTP requests */
  allowBatchedHttpRequests?: boolean;
}

type DataSources<TContext> = {
  [name: string]: DataSource<TContext>;
};

Persisted Queries Configuration

Configuration for persisted queries to improve performance and security.

interface PersistedQueryOptions {
  /** Cache implementation for persisted queries */
  cache?: KeyValueCache;
  
  /** Time-to-live for cached queries (in seconds, null = infinite) */
  ttl?: number | null;
}

Persisted Queries Example:

import { InMemoryLRUCache } from '@apollo/utils.keyvaluecache';

const server = new ApolloServerBase({
  typeDefs,
  resolvers,
  persistedQueries: {
    cache: new InMemoryLRUCache({
      maxSize: Math.pow(2, 20) * 30, // 30MB
      ttl: 300, // 5 minutes
    }),
  },
});

CSRF Prevention Configuration

Configuration for Cross-Site Request Forgery prevention.

interface CSRFPreventionOptions {
  /** Headers that must be present to prevent CSRF attacks */
  requestHeaders?: string[];
}

CSRF Prevention Example:

const server = new ApolloServerBase({
  typeDefs,
  resolvers,
  csrfPrevention: {
    requestHeaders: ['x-apollo-operation-name', 'apollo-require-preflight'],
  },
});

// Or use default CSRF prevention
const server = new ApolloServerBase({
  typeDefs,
  resolvers,
  csrfPrevention: true, // Uses default headers
});

Federation Gateway Configuration

Configuration for Apollo Federation gateway integration.

interface GatewayInterface {
  /** Load the gateway with Apollo configuration */
  load(options: { apollo: ApolloConfig }): Promise<GraphQLServiceConfig>;
  
  /** Subscribe to schema changes (deprecated) */
  onSchemaChange?(callback: SchemaChangeCallback): Unsubscriber;
  
  /** Subscribe to schema load/update events */
  onSchemaLoadOrUpdate?(
    callback: (schemaContext: {
      apiSchema: GraphQLSchema;
      coreSupergraphSdl: string;
    }) => void,
  ): Unsubscriber;
  
  /** Stop the gateway */
  stop(): Promise<void>;
}

interface GraphQLServiceConfig {
  schema: GraphQLSchema;
  executor: GraphQLExecutor | null;
}