Skip to content

Engine: Apollo

The Apollo Client setup: the client factory, the browser ApolloWrapper, the server client, cache policies, build-phase handling and the timing link that feeds Server-Timing.

Generated from packages/engine/src/apollo/: 8 files, 21 exported symbols. Signatures and types are shown as written in the source.

@magenxcommerce/engine/apollo/apollo-wrapper

packages/engine/src/apollo/apollo-wrapper.tsxclient

ApolloWrapper function

ApolloWrapper({ children, storeCode, }: { children: React.ReactNode; /** Magento Store View code to send in the `Store` header for every client * query. Pass the locale-resolved code from `[locale]/layout.tsx` so client * components fetch in the active locale. Falls back to the config's * `store.storeCode` (the default store view). */ storeCode?: string; })

@magenxcommerce/engine/apollo/build-phase

packages/engine/src/apollo/build-phase.ts

Whether this module graph is executing inside next build's prerender pass.

Lives in its own module (rather than in ./client, where it started) so ./build-skip can share the exact same signal without importing the client and creating a cycle. Read once at module scope: Next sets NEXT_PHASE before the build worker loads any app code, and it never changes mid-process.

BUILD_PHASE const

const BUILD_PHASE = process.env.NEXT_PHASE === "phase-production-build"

@magenxcommerce/engine/apollo/build-skip

packages/engine/src/apollo/build-skip.ts

Build-time handling for operations the storefront proxy will never forward.

WHY THIS EXISTS. next build prerenders against MAGENTO_GRAPHQL_BUILD_ENDPOINT, which points at the deployed site's own public /api/graphql (CI and image builds have no route into the internal docker network, and Magento's raw /graphql is not exposed to the internet). That route enforces the persisted-query allowlist — and a handful of engine operations are deliberately NOT on it. GetCmsBlocks is the clearest case: its content is rendered with dangerouslySetInnerHTML after being sanitized at the fetch boundary, so allowlisting it would let a browser pull the raw, unsanitized HTML straight from Magento (see SERVER_ONLY_OPERATIONS in apps/theme/src/app/api/graphql/_lib/allowed-operations.ts).

The result is a structural, expected build-vs-runtime asymmetry: at runtime these operations reach Magento directly and work; during prerender they get 403 "Operation not allowed". Every caller already fails soft (returns empty data under FALLBACK_CACHE_LIFE, so the content fills in on the first request after deploy — see ../magento/cache-life.ts for why that profile needs an expire and not just a short revalidate, and apps/theme/src/lib/cache-warm.ts for the boot warm-up that refills those entries before the first visitor rather than on their request), but the raw failure was extremely loud — Node dumps the whole ServerError including its Response object, once per call site per prerendered route, which reads like a broken build and buries real errors.

So: recognize that specific rejection, say what it means ONCE, and skip the network for every later call to the same operation. What this must NOT do is convert the failure into a success — the callers' catch blocks are what select cacheLife(FALLBACK_CACHE_LIFE) over the normal hour-long TTL, and that profile is exactly why the empty prerendered block repairs itself on the first request after deploy. Hence a compact error, not an empty result.

resetBuildSkipState function

resetBuildSkipState(): void

Test seam: the module-level set outlives a single test case.

isAllowlistRejection function

isAllowlistRejection(error: unknown): boolean

True for the allowlist's 403. Matched on both the status and the body so an unrelated 403 (a WAF, a proxy, an expired deployment) still surfaces in full rather than being quietly filed away as "expected".

isBuildSkip function

isBuildSkip(error: unknown): boolean

True for anything this module has already explained — the real 403 or our stand-in.

logQueryError function

logQueryError(label: string, error: unknown): void

Shared catch-block logger for the engine's server-side fetch helpers.

Identical to the console.error("<helper> error:", err) it replaces, except that a build-time allowlist skip is dropped: createBuildSkipLink has already reported it once, with an explanation the raw error doesn't carry.

@magenxcommerce/engine/apollo/cache-config

packages/engine/src/apollo/cache-config.ts

APOLLO_CACHE_CONFIG const

const APOLLO_CACHE_CONFIG: InMemoryCacheConfig

Shared Apollo InMemoryCache configuration used by both the server-side client (client.ts) and the client-side ApolloWrapper (apollo-wrapper.tsx).

Keeping this in one place avoids drift between the two when new Magento product types or cart item types are added.

@magenxcommerce/engine/apollo/client

packages/engine/src/apollo/client.ts

createApolloClient function

createApolloClient(storeCode?: string)

Create a new Apollo client. Pass storeCode to bind it to a specific Magento Store View (the value is sent in the Store GraphQL header).

No code, no header: Magento then answers in its own default store view. Never guess one — the literal default is the one value Magento's GraphQL header validator accepts WITHOUT checking that it exists, so a guess sails past the controller and fails deep inside a resolver with "The store that was requested wasn't found." Omitting the header is what PWA Studio's buildpack does too. Callers that know their locale pass its code (the theme's resolveStoreCode / getApolloForLocale).

There used to be a NEXT_PUBLIC_STORE_CODE build-arg fallback here. The theme now derives its store views from Magento at build time, and its default is Magento's default store view — the one an absent header already selects.

getServerApolloClient function

getServerApolloClient(storeCode?: string): ApolloClient

getApolloClient function

getApolloClient()

packages/engine/src/apollo/persisted-get-link.ts

@magenxcommerce/engine/apollo/persisted-query

packages/engine/src/apollo/persisted-query.ts

CACHEABLE_OPERATION_NAMES const

const CACHEABLE_OPERATION_NAMES: ReadonlySet<string>

Operations the browser may send as a hashed GET. Every entry must be:

  • a query in some feature's clientOperations (the policy suite checks this — a name that resolves to nothing fails CI, not production);
  • free of cart, customer and session input: its result must be the same for every guest given the same variables and store view, because one cached response is served to all of them;
  • not Turnstile-protected and not guest-only-by-auth (those decisions read request state a cached response cannot carry).

Adding a name here makes that operation's guest response cacheable at the edge for the TTL in the proxy's PERSISTED_GET_CACHE_CONTROL.

PERSISTED_GET_MAX_URL_LENGTH const

const PERSISTED_GET_MAX_URL_LENGTH = 4096

Longest GET URL the link will build before falling back to POST. nginx rejects a request line longer than one large_client_header_buffers buffer (8k by default) with 414; staying well under that leaves room for the headers sharing those buffers.

PERSISTED_GET_STORE_PARAM const

const PERSISTED_GET_STORE_PARAM = "store"

URL parameter carrying the Magento store view code on a GET.

PERSISTED_GET_CONTEXT_PARAM const

const PERSISTED_GET_CONTEXT_PARAM = "ctx"

URL parameter (ctx=1) marking a GET sent by a signed-in shopper.

canonicalizeDocument function

canonicalizeDocument(doc: DocumentNode): string

Canonical text of a document, for hashing. Apollo Client injects __typename into every selection set before a query goes on the wire, so the bytes it sends never equal print() of the engine document. Stripping un-aliased __typename and re-printing makes the hash invariant to that injection and to whitespace. The proxy allowlist hashes POST bodies with this same function, so a document that passes one passes the other.

operationNameOf function

operationNameOf(doc: DocumentNode): string | null

Name of the document's first operation, or null for a fragment-only one.

isQueryDocument function

isQueryDocument(doc: DocumentNode): boolean

True when the document's first operation is a query.

packages/engine/src/apollo/timing-link.ts