Skip to content
Lifestyle & Learning

Apollo Installations Explained: A Complete Guide to Apollo GraphQL Client, Server, and Router Architecture

In this article

Apollo installations refer to the process of provisioning, configuring, and deploying the core software modules of the Apollo GraphQL ecosystem—specifically Apollo Client for application frontends, Apollo Server for API services, and Apollo Router for federated microservices. Implementing Apollo enables engineering teams to construct unified, cached, and strongly typed data layers across client applications and backend systems.

While the term "Apollo installation" can occasionally refer to physical automated gate operators (such as Nice Apollo systems) or high-end audio interfaces (Universal Audio Apollo hardware), in modern software engineering and enterprise architecture, it overwhelmingly denotes the deployment of the Apollo GraphQL platform. This guide focuses entirely on software architecture, detailing how to install, configure, troubleshoot, and optimize Apollo components across client and server environments.

Understanding the Apollo Software Architecture

Before installing any individual software package, it is essential to understand how Apollo functions within a modern web or mobile technology stack. Apollo is not a single monolith; rather, it is a modular suite of tools designed to implement the GraphQL specification. A complete enterprise Apollo installation generally consists of three distinct tiers:

  1. Client Tier (Apollo Client): A declarative, spec-compliant state management library for web applications (React, Vue, Angular, Next.js) and mobile platforms (iOS, Android, React Native). It manages data fetching, normalized caching, optimistic UI updates, and local state management.

  2. Server Tier (Apollo Server): An open-source, spec-compliant GraphQL server that transforms existing databases, REST APIs, and microservices into a unified GraphQL API endpoint.

  3. Routing and Gateway Tier (Apollo Router & GraphOS): A high-performance, Rust-based API router that sits in front of multiple subgraphs in an enterprise Apollo Federation setup. It routes incoming client queries to the appropriate backend microservices and stitches response payloads into a single result.

  4. CLIENT TIER

    • [ React / Next.js / Mobile Application ] with @apollo/client
    • GraphQL HTTP/WS
  5. ROUTING TIER

    • Apollo Router (Rust Gateway) / GraphOS Schema Registry
    • Federated Subgraph Execution Plans
  6. SERVER TIER

    • [ Apollo Server 1 ] (User Subgraph)
    • [ Apollo Server 2 ] (Order Subgraph)
    • [ Legacy REST/DB ] (External APIs)

Each tier requires specific installation procedures, runtime environments, and configuration strategies. Setting up an Apollo installation correctly requires selecting the right modules for your application's operational boundaries.

Apollo Client Installation and Frontend Setup

Apollo Client is the primary interface through which client-side applications request and store data. It replaces traditional fetch wrappers and state containers like Redux by managing network requests and local cache storage in one integrated client.

System Prerequisites

To install Apollo Client, your development environment must have a modern JavaScript/TypeScript runtime installed.

  • Node.js: Active LTS version (v18.x or later recommended). Downloadable via the official Node.js project site.
  • Package Manager: npm, yarn, or pnpm.
  • UI Framework: While Apollo Client works with vanilla JavaScript, it provides native hooks for framework ecosystems such as React.

Package Installation

To install the core Apollo Client library along with its mandatory peer dependency, graphql, run the following command in your project root:

npm install @apollo/client graphql

  • @apollo/client contains the core engine, cache implementation, HTTP links, and React hooks (useQuery, useMutation, useSubscription).
  • graphql provides the core parsing, validation, and execution logic mandated by the GraphQL spec.

Initializing Apollo Client

Configuring an Apollo Client instance requires defining an HttpLink to specify your backend GraphQL URI and an InMemoryCache to store retrieved data in a normalized structure.

import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink } from '@apollo/client'; import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; // Define HTTP Connection to GraphQL API const httpLink = new HttpLink({ uri: 'https://api.example.com/graphql', headers: { authorization: localStorage.getItem('token') || '', }, }); // Initialize Client with Normalized Cache const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache({ typePolicies: { Query: { fields: { // Custom cache field policies can be defined here }, }, }, }), connectToDevTools: process.env.NODE_ENV !== 'production', }); // Render Root Application Wrapped in ApolloProvider const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( );

Understanding Apollo Client Network Links

Apollo Client uses a chainable link architecture (ApolloLink) to modify GraphQL requests before sending them over the network. Common link configurations installed alongside the core package include:

  • BatchHttpLink: Combines multiple GraphQL queries into a single HTTP POST request to reduce HTTP round-trips.
  • WebSocketLink (graphql-ws): Directs GraphQL subscription operations over persistent WebSocket connections for real-time updates.
  • ErrorLink: Captures global GraphQL and network errors to log telemetry or trigger token refreshes.

Apollo Server Installation and Backend Setup

Apollo Server provides the execution engine that receives incoming GraphQL queries, validates them against a schema, and executes resolver functions to retrieve data from underlying resources.

Installation Options: Standalone vs. Middleware

When installing Apollo Server, developers can choose between a zero-dependency standalone server or integrating Apollo Server as middleware into an existing web framework like Express, Fastify, or Next.js.

Option 1: Standalone Server Installation

The standalone setup is optimal for microservices dedicated exclusively to serving a GraphQL API.

npm install @apollo/server graphql

Create an entry point file (e.g., server.ts):

import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; // Define GraphQL Schema (TypeDefs) const typeDefs = `#graphql type User { id: ID! name: String! email: String! } type Query { users: [User!]! user(id: ID!): User } `; // Define Resolvers const resolvers = { Query: { users: () => [ { id: '1', name: 'Alice', email: 'alice@example.com' }, { id: '2', name: 'Bob', email: 'bob@example.com' }, ], user: (_: unknown, args: { id: string }) => ({ id: args.id, name: 'Alice', email: 'alice@example.com', }), }, }; // Instantiation const server = new ApolloServer({ typeDefs, resolvers, }); // Start Server const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }); console.log(`🚀 Apollo Server ready at: ${url}`);

Option 2: Express Middleware Installation

If your backend must serve REST endpoints, host static assets, or use existing Express middleware (such as Passport.js for authentication), install the Express integration package:

npm install @apollo/server graphql express cors body-parser

In this architecture, Apollo Server attaches to specific routes (typically /graphql), leaving the rest of the Express routing stack intact.

Enterprise Infrastructure: Apollo Router and Apollo Federation

In large enterprises, maintaining a single monolithic GraphQL schema server often leads to tight coupling across engineering teams. Apollo Federation resolves this by allowing teams to build independent subgraphs that combine into a unified supergraph.

The Role of Apollo Router

The Apollo Router is a high-performance routing binary written in Rust. It serves as the entrance point for client queries in federated architectures, replacing older Node.js-based gateway implementations due to significantly higher throughput, lower latency, and reduced memory footprint.

# Example script to download the Apollo Router binary directly curl -sSL https://router.apollo.dev/download/nix/latest | sh

Alternatively, Apollo Router is distributed as an official Docker container via Docker Hub, making it straightforward to deploy on Kubernetes, AWS ECS, or Google Cloud Run.

Configuring standard Subgraphs

Each backend microservice installs @apollo/subgraph alongside @apollo/server to expose federated schemas using GraphQL entity directives (@key, @extends, @external).

import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; import { buildSubgraphSchema } from '@apollo/subgraph'; import gql from 'graphql-tag'; const typeDefs = gql` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type Product @key(fields: "id") { id: ID! name: String! price: Float! } `; const resolvers = { Product: { __resolveReference(productRef: { id: string }) { return { id: productRef.id, name: 'Sample Product', price: 99.99 }; }, }, }; const server = new ApolloServer({ schema: buildSubgraphSchema({ typeDefs, resolvers }), }); await startStandaloneServer(server, { listen: { port: 4001 } });

Schema Composition with Rover CLI

To deploy federated Apollo installations, schemas from each subgraph must be composed into a core supergraph schema. The Rover CLI is Apollo's official command-line tool used in continuous integration pipelines to validate, compose, and publish schemas to Apollo GraphOS.

# Install Rover CLI curl -sSL https://rover.apollo.dev/nix/latest | sh # Compose local subgraphs into a supergraph schema file rover supergraph compose --config ./supergraph-config.yaml > supergraph.graphql

Comprehensive Architecture Comparison

Choosing the correct packages and installation patterns depends on where the software component resides within your application architecture.

Software Module Primary Package / Binary Target Environment Key Responsibility Primary Dependencies
Apollo Client @apollo/client Web Browsers, Mobile Apps, Desktop Frontends Declarative data fetching, normalized caching (InMemoryCache), UI state sync. graphql, react (optional)
Apollo Server (Standalone) @apollo/server Node.js Runtime Standalone execution of GraphQL schemas, type definitions, and resolvers. graphql
Apollo Server (Express) @apollo/server, @apollo/server/express4 Node.js / Express Web Applications Integrating GraphQL handling into existing HTTP application routing stacks. graphql, express, cors
Apollo Subgraph @apollo/subgraph Node.js Microservices Exposing federated entity schemas to an enterprise router or gateway. @apollo/server, graphql
Apollo Router apollo-router (Rust Binary / Container) Edge / API Gateway Infrastructure Processing client requests, executing plan orchestration across microservices. Independent Rust Binary / Docker
Rover CLI rover (Native Binary) Developer Machines / CI/CD Pipelines Schema linting, validation, breaking change detection, and supergraph composition. Executable CLI tool

Advanced Configuration: Caching, State, and Networking

A basic Apollo Client installation fetches data over HTTP, but leveraging its full potential requires configuring state management and caching policies.

Normalized Caching Mechanisms

Unlike simple key-value HTTP caches that store full JSON payloads keyed by URL, Apollo Client's InMemoryCache normalizes incoming response data. It flattens nested objects into discrete key-value pairs stored by __typename and id (or _id).

For example, a query fetching an author and their posts will split the response payload into distinct entities in the cache:

  • Author:42 -> { id: "42", name: "Jane Doe" }
  • Post:101 -> { id: "101", title: "Apollo Installations", author: { __ref: "Author:42" } }

If another component queries Author:42, Apollo Client instantly returns the cached object without triggering an unnecessary network request.

Custom Cache Type Policies

If your data model uses unique primary keys other than id, or requires field-level pagination merging, define explicit typePolicies:

const cache = new InMemoryCache({ typePolicies: { Product: { keyFields: ['productSKU'], // Custom primary key mapping }, Query: { fields: { feed: { // Merge offset-based pagination results into a single array keyArgs: false, merge(existing = [], incoming) { return [...existing, ...incoming]; }, }, }, }, }, });

Local State Management via Reactive Variables

Apollo Client allows developers to manage local application state without needing secondary state containers like Redux. Reactive Variables operate independently of the cache, allowing components to read and react to changes seamlessly.

import { makeVar, useReactiveVar } from '@apollo/client'; // Create a reactive variable for user cart items export const cartItemsVar = makeVar([]); // React Component standard consumption function CartCounter() { const cartItems = useReactiveVar(cartItemsVar); return Items in cart: {cartItems.length}; } // Mutating local state anywhere in the application function addToCart(productId: string) { const current = cartItemsVar(); cartItemsVar([...current, productId]); }

Troubleshooting Common Apollo Installation Issues

During setup, developers often encounter common configuration errors across client and server boundaries. Here are practical solutions for resolving them.

1. Peer Dependency Mismatches (graphql Package Version Conflict)

Symptom: Terminal outputs ERR_PNPM_PEER_DEP_ISSUES or npm warnings stating that @apollo/client requires a different version of graphql.

Cause: Installing multiple libraries that depend on conflicting semver ranges of graphql. Installing two different versions of graphql within the same node_modules tree causes runtime execution failures because instanceof checks on schema types fail.

Solution: Align all graphql dependencies to a single major version across your package.json:

{ "dependencies": { "@apollo/client": "^3.10.0", "graphql": "^16.8.0" } }

If lockfiles preserve duplicate packages, clear node_modules and re-run installation commands using deduplication flags (npm dedupe).

2. CORS Errors in Apollo Server Setup

Symptom: Web browsers block frontend GraphQL queries with messages stating No 'Access-Control-Allow-Origin' header is present on the requested resource.

Cause: Apollo Server is hosted on a different domain or port than the frontend application, and cross-origin resource sharing (CORS) is unconfigured.

Solution: When using Express integration, configure the cors package to explicitly allow your frontend origin and standard GraphQL headers:

import cors from 'cors'; import express from 'express'; import { expressMiddleware } from '@apollo/server/express4'; const app = express(); app.use( '/graphql', cors({ origin: ['https://yourfrontend.com', 'http://localhost:3000'], credentials: true, }), express.json(), expressMiddleware(server) );

3. React SSR Hydration Mismatches (Next.js / Remix)

Symptom: Warning messages during server-side rendering (SSR) stating Text content does not match server-rendered HTML.

Cause: The Apollo Client cache populated during server rendering was not serialized and passed to the client runtime. As a result, the browser attempts to fetch data again on render, causing an initial HTML mismatch.

Solution: Extract the cache state on the server using getDataFromTree or framework-native props, and hydrate it on the client using cache.restore(window.__APOLLO_STATE__).

Security and Production Readiness

Deploying Apollo installations to production environments requires strict operational safeguards to protect backend services from abusive queries and resource exhaustion.

  1. Incoming Request
  2. Disable Introspection: Prevents public schema discovery
  3. Query Depth Limit: Rejects deeply nested queries
  4. Operations Allowed List: Executes pre-approved queries only
  5. Execute Resolvers

Disabling Introspection and Schema Schema Polling

By default, Apollo Server allows clients to run introspection queries (__schema), which tools like GraphQL Playground or Postman use to visualize your entire database structure. Introspection should be disabled in public production deployments unless your API is explicitly intended for public developer access.

const server = new ApolloServer({ typeDefs, resolvers, introspection: process.env.NODE_ENV !== 'production', });

Query Depth Limiting and Complexity Control

Because GraphQL allows nested relational queries (e.g., user -> posts -> author -> posts -> author), malicious clients can craft deeply nested queries that exhaust server CPU and database connections.

To prevent this, install query depth and validation plugins such as graphql-depth-limit:

npm install graphql-depth-limit

Add validation rules to your Apollo Server configuration:

import depthLimit from 'graphql-depth-limit'; const server = new ApolloServer({ typeDefs, resolvers, validationRules: [depthLimit(5)], // Limits query nesting to a maximum of 5 levels });

Automated CI/CD Schema Checks

To prevent developers from accidentally introducing breaking changes into production schemas (such as removing a field currently used by active mobile clients), integrate the Rover CLI into your GitHub Actions or GitLab CI pipelines.

# Example GitHub Action Step - name: Validate Schema against Apollo GraphOS run: | rover subgraph check my-graph@production \ --name user-subgraph \ --schema ./schema.graphql env: APOLLO_KEY: ${{ secrets.APOLLO_KEY }}

Frequently Asked Questions

What packages are required for a minimal Apollo Client installation?

A minimal client setup requires @apollo/client and graphql. If you are building inside a React application, @apollo/client provides native hooks directly out of the box without needing additional wrapper packages.

How does Apollo Server standalone mode differ from Express middleware integration?

Standalone mode (startStandaloneServer) includes an HTTP server out of the box, making it simple to spin up dedicated GraphQL microservices with zero external server code. Middleware integration (expressMiddleware) attaches Apollo handling directly to an existing Express app, allowing you to use custom routes, REST handlers, and pre-existing authentication middleware.

What is the role of Apollo Router in enterprise installations?

Apollo Router is a high-performance Rust binary designed to route queries across federated subgraphs. It replaces legacy JavaScript gateways, executing query planning and processing payloads at microsecond speeds with significantly lower memory consumption.

How do I inspect and debug an Apollo Client installation?

Install the official Apollo Client DevTools browser extension (available for Chrome and Firefox). When enabled, it allows developers to inspect the normalized InMemoryCache, view active queries and mutations, trigger operations manually, and analyze network performance in real time.

Can Apollo Client be installed and used without React?

Yes. Apollo Client's core engine is framework-agnostic. It can be installed and integrated into vanilla JavaScript/TypeScript applications, Vue, Angular, Svelte, or backend Node.js scripts using the core ApolloClient constructor directly.

Summary and Recommended Next Steps

Setting up an Apollo installation requires matching the right architectural components to your project's specific operational needs. For frontend client applications, focus on proper InMemoryCache configuration and clear network link management. For backend microservices, implement secure Apollo Server instances or build out a federated architecture using Apollo Router to achieve horizontal scalability.

Next Steps for Implementation:

  1. Frontend Setup: Install @apollo/client and graphql, wrap your root component in ApolloProvider, and verify cache behavior with Apollo DevTools.
  2. Backend Setup: Define your schema using standard GraphQL Type Definitions, implement strongly typed resolver functions, and attach security controls like depth-limiting.
  3. CI/CD Integration: Integrate Rover CLI schema checks into your automated build pipelines to guard against breaking changes across client applications.

For detailed API references, syntax updates, and migration blueprints, review the official Apollo Developer Documentation.