by Maya Torres

Apollo Client is the industry-leading GraphQL client for TypeScript, JavaScript, React, Vue, Angular, and more, offering zero-config caching, full type safety, and powerful developer tools.
This block ships the full Apollo Client v4 source (@apollo/client@4.1.7) into your project, giving you a production-grade GraphQL client with normalized caching, reactive queries, link-chain middleware, and incremental delivery support. The typical buyer is a TypeScript backend-for-frontend team, framework-agnostic Node.js service, or a React/Vue/Angular app that wants to own the client source for auditing, patching, or vendoring.
cache/ - Normalized InMemoryCache, entity store, reactive variables, and cache policy engineconfig/ - Jest resolver and custom equality matchers for GraphQL error types in testscore/ - ApolloClient, ObservableQuery, QueryManager, QueryInfo, network status enum, and all core typesdev/ - Utilities for loading human-readable dev/error messages in development buildserrors/ - Typed error classes (CombinedGraphQLErrors, ServerError, LinkError, etc.) and helpersincremental/ - Handlers for GraphQL incremental delivery (@defer, @stream) protocol variantslink/ - Composable link chain middleware (batch, batch-http, context, error, core, client-awareness)local-state/ - Local resolver and reactive variable integration for client-side statemasking/ - Fragment data masking utilitiesreact/ - React hooks, context, and component bindingstesting/ - MockLink, MockedProvider, and test utilitiesutilities/ - Shared internal helpers (AST, observable, fragment matching, type merging)invariantErrorCodes.ts - Mapping of invariant assertion codes to error messagesv4-migration.ts - Compatibility shims for v3-to-v4 migrationversion.ts - Package version constantnpm install graphql graphql-tag optimism @wry/equality @wry/caches @wry/trie @graphql-typed-document-node/core tslib
No native modules, pod installs, or Android linking are required. This is pure TypeScript/JavaScript.
Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 39a5be7d9d08aee3…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
Copy the source/ directory into your project, e.g. src/apollo-client/.
Update tsconfig.json to include the source and enable the necessary options:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"strict": true,
"paths": {
"@apollo/client/*": ["./src/apollo-client/*"]
}
},
"include": ["src"]
}
If you use graphql-tag with .graphql file imports, configure your bundler (webpack/esbuild/vite) to handle .graphql files with graphql-tag/loader.
The source uses .js extension in relative imports (ESM style). If you're targeting CommonJS, set "moduleResolution": "Node16" or transpile through a bundler that resolves .js → .ts extensions (e.g. ts-node with --esm, or tsx).
No environment variables are required for the core client. The dev/ utilities (loadDevMessages, loadErrorMessages) are opt-in for development builds only.
import { ApolloClient } from "./src/apollo-client/core/ApolloClient.js";
import { InMemoryCache } from "./src/apollo-client/cache/inmemory/inMemoryCache.js";
import { HttpLink } from "./src/apollo-client/link/http/index.js";
const client = new ApolloClient({
link: new HttpLink({ uri: "https://example.com/graphql" }),
cache: new InMemoryCache(),
});
The central orchestrator: manages query/mutation/subscription lifecycle, maintains the cache, and routes operations through the link chain. Instantiate once per application and share via context or a module singleton.
import { InMemoryCache } from "./src/apollo-client/cache/inmemory/inMemoryCache.js";
import type { InMemoryCacheConfig } from "./src/apollo-client/cache/inmemory/types.js";
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
todos: { merge: (existing = [], incoming) => [...existing, ...incoming] },
},
},
},
} satisfies InMemoryCacheConfig);
The default normalized cache implementation. Pass typePolicies to control key extraction, field merging, and pagination. Used as the cache option for ApolloClient.
import { makeVar } from "./src/apollo-client/cache/inmemory/reactiveVars.js";
import type { ReactiveVar } from "./src/apollo-client/cache/inmemory/reactiveVars.js";
const cartItemsVar: ReactiveVar<string[]> = makeVar<string[]>([]);
// Read
const current = cartItemsVar();
// Write
cartItemsVar([...current, "item-123"]);
Creates a reactive variable that lives outside the normalized cache but integrates with Apollo's reactivity model. Queries that read a reactive variable automatically re-render when the variable changes. Use for local client-side state that doesn't come from the server.
import { CombinedGraphQLErrors } from "./src/apollo-client/errors/CombinedGraphQLErrors.js";
try {
await client.query({ query: MY_QUERY });
} catch (e) {
if (e instanceof CombinedGraphQLErrors) {
for (const err of e.graphQLErrors) {
console.error(err.message, err.path);
}
}
}
Thrown when a GraphQL response contains one or more errors. Wraps the raw error array with a typed interface. Use in catch blocks to distinguish GraphQL-level errors from network-level errors.
Run a one-shot query from a Node.js script, logging the result.
import { ApolloClient } from "./src/apollo-client/core/ApolloClient.js";
import { InMemoryCache } from "./src/apollo-client/cache/inmemory/inMemoryCache.js";
import { gql } from "graphql-tag";
const client = new ApolloClient({
uri: "https://countries.trevorblades.com/",
cache: new InMemoryCache(),
});
const COUNTRIES = gql`
query GetCountries {
countries {
code
name
}
}
`;
const result = await client.query({ query: COUNTRIES });
console.log(result.data.countries);
Manage a shopping cart entirely on the client without a server round-trip.
import { makeVar } from "./src/apollo-client/cache/inmemory/reactiveVars.js";
import { InMemoryCache } from "./src/apollo-client/cache/inmemory/inMemoryCache.js";
import { ApolloClient } from "./src/apollo-client/core/ApolloClient.js";
import { gql } from "graphql-tag";
export const cartVar = makeVar<string[]>([]);
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
cart: { read: () => cartVar() },
},
},
},
});
const client = new ApolloClient({ cache, uri: "/graphql" });
// Add item
cartVar([...cartVar(), "product-42"]);
// Read via cache field
const { data } = await client.query({
query: gql`query { cart }`,
fetchPolicy: "cache-only",
});
console.log(data.cart); // ["product-42"]
Distinguish network errors from GraphQL errors in an async mutation.
import { ApolloClient } from "./src/apollo-client/core/ApolloClient.js";
import { InMemoryCache } from "./src/apollo-client/cache/inmemory/inMemoryCache.js";
import { CombinedGraphQLErrors } from "./src/apollo-client/errors/CombinedGraphQLErrors.js";
import { ServerError } from "./src/apollo-client/errors/ServerError.js";
import { gql } from "graphql-tag";
const client = new ApolloClient({ uri: "/graphql", cache: new InMemoryCache() });
const CREATE_USER = gql`
mutation CreateUser($name: String!) {
createUser(name: $name) { id name }
}
`;
async function createUser(name: string) {
try {
const { data } = await client.mutate({
mutation: CREATE_USER,
variables: { name },
});
return data.createUser;
} catch (err) {
if (err instanceof CombinedGraphQLErrors) {
console.error("Validation errors:", err.graphQLErrors.map((e) => e.message));
} else if (err instanceof ServerError) {
console.error("HTTP error:", err.statusCode, err.message);
} else {
throw err;
}
}
}
Enable human-readable invariant error messages during local development.
import { loadErrorMessages, loadDevMessages } from "./src/apollo-client/dev/index.js";
if (process.env.NODE_ENV !== "production") {
loadErrorMessages();
loadDevMessages();
}
cache/ - Contains ApolloCache base class, InMemoryCache, entity store (normalized data), reactive vars, and type/field policies. The cache is the heart of Apollo's performance story.core/ - ApolloClient orchestrates all operations; QueryManager handles request deduplication and polling; ObservableQuery exposes reactive query results; networkStatus.ts defines the loading-state enum.dev/ - Opt-in dev helpers that attach verbose error messages to invariant assertions; import only in non-production builds.errors/ - Typed error hierarchy. CombinedGraphQLErrors wraps errors[] from a response; ServerError wraps HTTP-level failures; LinkError wraps link-chain errors.incremental/ - Protocol handlers for @defer/@stream incremental delivery. Defer20220824Handler implements the 2022-08-24 spec draft; GraphQL17Alpha9Handler targets the alpha-9 reference implementation.link/ - Middleware chain system. link/core/ defines ApolloLink and concat/from/split; link/batch/ and link/batch-http/ batch multiple operations; link/error/ intercepts errors; link/context/ sets request context.local-state/ - Bridges local resolvers and reactive variables into the query execution path.masking/ - Enforces fragment data masking so components only access their own fragment data.react/ - Hooks (useQuery, useMutation, useSubscription, useLazyQuery), context provider, and HOCs.testing/ - MockLink and MockedProvider for unit-testing components without a real server.utilities/ - Internal shared utilities: observable helpers, AST transforms, type policies merging, and canonicalStringify.invariantErrorCodes.ts - Numeric-to-message lookup table used by invariant assertions in production bundles.v4-migration.ts - Re-exports and shims to ease migration from Apollo Client v3.version.ts - Exports the string "4.1.7" for runtime version checks..js extension resolution fails in ts-node CJS mode - Add "moduleResolution": "Node16" to tsconfig.json and run ts-node with --esm, or use tsx instead.graphql version mismatch causes "Cannot use GraphQLSchema from another module" - Pin a single graphql version in package.json using "resolutions" (Yarn) or "overrides" (npm ≥7).optimism recompute loops in SSR - Do not share a single ApolloClient instance across requests; create a new instance per server-side render.ReactiveVar inside a read() function, not at module initialization time.format: "cjs" explicitly to avoid mixed module graphs.InMemoryCache stores stale data after logout - Call client.clearStore() (async, broadcasts) or client.resetStore() (re-fetches active queries) on logout; never mutate the cache object directly.I have vendored the Apollo Client v4 source into `src/apollo-client/` and
have a USAGE.md at the root of this project describing its full API and
structure. The upstream package is `@apollo/client@4.1.7`.
Please help me integrate Apollo Client into my project step by step:
1. Read USAGE.md and the relevant files under `src/apollo-client/` to
understand the real exports and signatures before writing any code.
2. Set up an `ApolloClient` instance with `InMemoryCache` pointing to my
GraphQL endpoint at [INSERT YOUR ENDPOINT HERE].
3. Wire it into my application entry point ([INSERT YOUR ENTRY FILE]).
4. Add a typed query using `gql` from `graphql-tag` for [DESCRIBE YOUR QUERY].
5. Add error handling that distinguishes `CombinedGraphQLErrors` from
`ServerError` using the typed error classes in `src/apollo-client/errors/`.
6. If I am using React, add the `ApolloProvider` from
`src/apollo-client/react/` and a `useQuery` hook call.
7. Show me how to write a unit test using `MockedProvider` from
`src/apollo-client/testing/`.
Do not import from `@apollo/client` directly. Import from the local
`src/apollo-client/` paths shown in USAGE.md. Only use symbols that are
explicitly exported in the index files shown in USAGE.md.
Apollo Client is released under the MIT License. See source/LICENSE if present, or refer to the official repository. Upstream package: @apollo/client by Apollo GraphQL.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free