Skip to content

Engine: Magento helpers

Server-side Magento access: the GraphQL documents barrel, shared types, and the cached catalog, store and GDPR fetch helpers used by server components. The helpers use 'use cache', so import them by deep path, never through the client-reachable barrel.

Generated from packages/engine/src/magento/: 4 files, 44 exported symbols. Signatures and types are shown as written in the source.

@magenxcommerce/engine/magento/cache-life

packages/engine/src/magento/cache-life.ts

Cache lifetime for a fetch that fell back to empty data.

WHY THIS EXISTS. Every 'use cache' helper in this directory fails soft: an unreachable Magento, or an operation the build endpoint's allowlist rejects (see ../apollo/build-skip.ts), returns an empty value instead of throwing. The short revalidate was already here so that empty value would not survive a full TTL window — but revalidate alone was NOT enough, and the gap is what made a freshly booted container serve CMS-less pages:

  `cacheLife`'s `expire` defaults to NEVER. Past `revalidate`, an entry is
  stale-but-servable forever: the request that finds it gets the STALE value
  and only kicks off a background refresh. So the empty CMS blocks baked into
  the prerender by `next build` (hours old, long past a 10s revalidate) were
  handed to the first real visitor as-is; the refresh landed a moment later,
  which is why the content appeared "after a refresh" and not before.

Setting expire closes it: once an entry is older than expire, the next request regenerates it SYNCHRONOUSLY and is answered with real content. A build-time empty is always older than that by the time the container boots, so the very first request after boot renders the live CMS block.

300s, not something tighter, because Next.js excludes a cache scope whose expire is UNDER five minutes from prerenders entirely (it becomes a dynamic hole resolved per request). That would quietly drop these pages out of the static build — the opposite of what this stack is for. 300 is the smallest value that keeps the prerender and still expires. Next also validates expire > revalidate.

Boot is additionally covered by the storefront's cache warm-up (apps/theme/src/lib/cache-warm.ts), which purges and re-primes the tags the build could not fetch before the first visitor arrives. That handles the one window this profile cannot: a container booting within expire seconds of the build that produced its prerenders.

TTL_ERROR const

const TTL_ERROR = 10

Seconds an empty/failed result stays fresh. Short so the next runtime request — when Magento IS reachable — refetches instead of serving the fallback for the helper's normal TTL.

TTL_ERROR_EXPIRE const

const TTL_ERROR_EXPIRE = 300

Seconds after which a fallback entry stops being servable at all and the next request must wait for fresh data. See the note above for why this is exactly 300 and not lower.

FALLBACK_CACHE_LIFE const

const FALLBACK_CACHE_LIFE = { revalidate: TTL_ERROR, expire: TTL_ERROR_EXPIRE, }

cacheLife profile for every fail-soft / empty branch in this directory. Pass it at the call site (cacheLife(FALLBACK_CACHE_LIFE)) so the branch's cache behaviour stays visible where the fallback is returned.

@magenxcommerce/engine/magento/catalog

packages/engine/src/magento/catalog.ts

ProductReviewsResult interface

Below-the-fold PDP reviews, fetched separately from getProductBySlug.

MemberTypeDescription
reviews?ProductReviewsOutput

ProductLinkedProducts interface

Below-the-fold PDP linked products, fetched separately from everything else.

MemberTypeDescription
related_productsProductInterface[]
upsell_productsProductInterface[]
frequently_bought_together_productsProductInterface[]

getCategoryBySlug function

async getCategoryBySlug(storeCode: string, slug: string): Promise<CategoryTree | null>

getProductsByCategory function

async getProductsByCategory(args: GetProductsByCategoryArgs): Promise<ProductsOutput>

getSpecialProducts function

async getSpecialProducts(args: { storeCode: string; categoryUid: string; }): Promise<ProductInterface[]>

Products in a category flagged with the Yes/No special attribute — the pool the category page picks its wide "special" card from. Filters are NOT applied: the card features the category, not the current filter state.

Returns [] on any error. That includes the store not having a filterable special attribute (Magento then rejects the filter field), so the page simply renders without the card.

CategoryAggregations type

type CategoryAggregations = NonNullable<ProductsOutput["aggregations"]>

getCategoryAggregations function

async getCategoryAggregations(args: GetCategoryAggregationsArgs): Promise<CategoryAggregations>

Layered-navigation facets for the category filter sidebar, fetched separately from the product grid (GET_CATEGORY_AGGREGATIONS) so the grid renders without waiting on Magento's expensive aggregation computation. Tagged with the grid's category identities, so a category save or a change to the category's product set invalidates both. It carries no per-product cat_p_<id> tags (the facets list no products), so an attribute edit on an existing product reaches the facet counts only through TTL_PRODUCT_LIST. Fails soft to [] so a slow/erroring facet query never blocks the grid.

getProductsByManufacturer function

async getProductsByManufacturer(args: GetProductsByManufacturerArgs): Promise<ProductsOutput>

Product grid for a single brand, matched by exact manufacturer attribute value rather than free-text search — used by /search when q matches a known brand title (see brand-match logic in the search page). Reuses GET_PRODUCTS_BY_CATEGORY as-is: the query is generic over $filters, no category-specific fields.

getManufacturerAggregations function

async getManufacturerAggregations(args: GetManufacturerAggregationsArgs): Promise<CategoryAggregations>

Layered-navigation facets for the brand-matched /search filter drawer, fetched separately from the grid (GET_CATEGORY_AGGREGATIONS, same generic filter-driven query used by category pages). Fails soft to [].

getBestSellers function

async getBestSellers(storeCode: string, categoryId?: number | null, pageSize?: number): Promise<BestSellerItem[]>

Top best-selling products, store-wide (categoryId omitted) or scoped to a single category. Returns ranked entries with their product hydrated as a card-shaped ProductInterface; entries whose product is no longer available are dropped. Server-only (runs via the server Apollo client, bypasses the /api/graphql proxy), and GET_BEST_SELLERS is NOT in the persisted-query allowlist: the browser reads this same cached entry through the /api/best-sellers route. Tagged with each product's identity so a product save / report reindex purge refreshes it; fails soft to [].

getDeals function

async getDeals(storeCode: string, type?: DealType | null, pageSize?: number): Promise<ProductInterface[]>

Products currently on an active deal campaign, optionally filtered to one DealType. Each entry's product is hydrated as a card-shaped ProductInterface (its deal field carries the campaign metadata); entries whose product is no longer available are dropped. Server-only (runs via the server Apollo client, bypasses the /api/graphql proxy), and GET_DEALS is NOT in the persisted-query allowlist: the /deals page renders the store-wide entry and the browser reads the same cached entries through the /api/deals route. Tagged with each product's identity so a product save / config purge refreshes it; fails soft to [].

getGiftDeals function

async getGiftDeals(storeCode: string): Promise<GiftDeal[]>

Gift deals live now for the store view's guest group (Magenx_DealGraphQl): coupon-less Cart Price Rules that add a free product while they apply. Entries whose gift product is unavailable are dropped. Server-only, like getDeals; fails soft to [].

getCouponDeals function

async getCouponDeals(storeCode: string): Promise<CouponDeal[]>

Coupon deals for the store view's guest group (Magenx_DealGraphQl): the coupon codes the merchant marked "Show on Storefront", usable now. One cached entry per store view serves the /deals "Coupons" tab and every product page's coupon strip, so a PDP costs no Magento query for it. Entries without a code are dropped. Server-only; fails soft to [].

getProductBySlug function

async getProductBySlug(storeCode: string, slug: string): Promise<ProductInterface | null>

getProductReviews function

async getProductReviews(storeCode: string, sku: string): Promise<ProductReviewsResult>

Below-the-fold PDP reviews, split out of getProductBySlug so the critical (LCP) product query stays lean. The PDP fires this without awaiting and streams the result through a <Suspense> boundary. Fails soft to empty so a slow/erroring query never blocks or breaks the product page (the core product already rendered).

This and getProductLinkedProducts were one helper until 2026-08-14. They were separated because the shared fail-soft meant one slow linked-product resolver returned an empty result for BOTH, silently emptying the reviews block and stripping the review array out of the PDP's Product JSON-LD. Reviews are cheap and SEO-bearing; linked products are three full product resolutions. They do not belong in the same failure domain.

getProductLinkedProducts function

async getProductLinkedProducts(storeCode: string, sku: string): Promise<ProductLinkedProducts>

Below-the-fold PDP linked products (related / up-sell / frequently bought together). The expensive half of the old combined relations query — three full product resolutions.

Unlike getProductReviews this is NOT streamed with the page: the PDP serves it from app/api/product-links/route.ts, which the storefront calls only once the shopper scrolls near the grids. That keeps its result out of every PDP's flight payload while KEEPING this cache entry, which is why the fetch goes through a route handler rather than the browser's GraphQL proxy (the proxy responds Cache-Control: no-store, so a client-run query would turn one cached resolution per 6h into one live Magento query per scrolling visitor).

Fails soft to empty — a missing merchandising rail is not worth an error page.

getHomepageCategoryProducts function

async getHomepageCategoryProducts(args: GetHomepageCategoryProductsArgs): Promise<ProductInterface[]>

getCategoriesByUrlKeys function

async getCategoriesByUrlKeys(storeCode: string, urlKeys: readonly string[]): Promise<CategoryTree[]>

getNavigationCategories function

async getNavigationCategories(storeCode: string): Promise<CategoryTree[]>

Fetch the top-level store navigation tree (root + 2 levels of children) for storeCode. The nav rarely changes and is identical for every visitor, so it's cached with a long TTL and shared store-wide: the layout renders it into the initial HTML and passes it to the (client) Header, so the browser never re-fetches GetNavigationCategories per page load. Invalidate via /api/revalidate with the ${storeCode}:navigation tag or any cat_c_<id> purge from Magento. Fails soft to [].

getTopLevelCategories function

async getTopLevelCategories(storeCode: string): Promise<CategoryTree[]>

Fetch the store's top-level menu categories (direct children of the root, include_in_menu on) as homepage category cards: name, link, image and product count, no children. Used by the homepage featured-categories carousel when cms.homepageCategoryUrlKeys is empty.

Reuses GetNavigationCategories rather than a new document so the persisted query hash stays on the /api/graphql allowlist (see toNavCategory). It can't share getNavigationCategories' cache entry because that one strips image, which only the homepage needs. Fails soft to [].

getCmsBlocks function

async getCmsBlocks(storeCode: string, identifiers: readonly string[]): Promise<CmsBlock[]>

getManufacturerBrands function

async getManufacturerBrands(storeCode: string): Promise<ManufacturerBrand[]>

searchProducts function

async searchProducts(args: SearchProductsArgs): Promise<ProductsOutput>

getSearchAggregations function

async getSearchAggregations(args: { storeCode: string; query: string; filters?: Record<string, string | string[] | undefined>; }): Promise<CategoryAggregations>

Layered-navigation facets for a search term, fetched separately from the results grid (SEARCH_PRODUCT_AGGREGATIONS) so the grid renders without waiting on Magento's expensive aggregation computation. One fetch feeds BOTH the search filter drawer and the "Found in these categories" strip. The active f_* filters are applied so facet counts reflect the narrowed set (mirrors getCategoryAggregations). Fails soft to [].

SearchCategoryFacet type

type SearchCategoryFacet

One category in the search "quick search" breakdown.

MemberTypeDescription
idstring
namestring
countnumber

SearchCategoryFacets type

type SearchCategoryFacets

The category facet of a search, plus which attribute code it came from.

MemberTypeDescription
attributeCodestring"category_uid" or "category_id" — whichever aggregation this Magento returned. Load-bearing for the filter pills: a pill link must set the matching f_<attributeCode> param or the filter silently won't apply.
itemsSearchCategoryFacet[]

extractSearchCategoryFacet function

extractSearchCategoryFacet(aggregations: CategoryAggregations, limit = 12): SearchCategoryFacets | null

Pure helper: extract the category breakdown ("which categories do the matches fall into?") from an already-fetched aggregations list. Returns null when Magento exposed no usable category facet.

getBlogPosts function

async getBlogPosts(args: GetBlogPostsArgs): Promise<BlogPostsOutput>

getBlogPostByUrlKey function

async getBlogPostByUrlKey(storeCode: string, urlKey: string): Promise<BlogPost | null>

getBlogTagByUrlKey function

async getBlogTagByUrlKey(storeCode: string, urlKey: string): Promise<BlogTag | null>

Fetch a blog tag and the published posts assigned to it, by url_key. Backs the /blog/tag/[key] route. Returns null if the tag does not exist.

getProductsBySkus function

async getProductsBySkus(storeCode: string, skus: string[]): Promise<ProductInterface[]>

Resolve full catalog product cards (name/price/image/rating) for a list of SKUs. Used to render the products a merchant assigned to a blog post, whose Post.products resolver only returns identity fields.

getBlogPostProducts function

async getBlogPostProducts(storeCode: string, post: BlogPost): Promise<ProductInterface[]>

Resolve the catalog products a merchant assigned to a blog post. Reads the lightweight SKU refs from the post's products sub-resolver and hydrates them into full product cards.

getBlogRelatedPosts function

async getBlogRelatedPosts(storeCode: string, productSku: string): Promise<BlogPost[]>

Find published blog posts that have a given product in their related products — server-side sku filter (BlogPostFilterInput), so this is a single filtered query, not a scan of every post.

Cached for TTL_PRODUCT_RELATIONS rather than TTL_BLOG: like the PDP's other below-the-fold relations it is fetched on scroll (/api/product-blog-posts), and a post save — the only thing that changes the post↔product link — purges the coarse blog tag immediately. What the TTL alone governs is a future-dated post going live with no save to purge it; the blog listings keep TTL_BLOG for that, while on a PDP's "related reading" row a few hours' delay costs nothing.

getBlogPostsByCategory function

async getBlogPostsByCategory(args: GetBlogPostsByCategoryArgs): Promise<BlogPostsOutput>

UrlSuffixes interface

MemberTypeDescription
productstring
categorystring

getUrlSuffixes function

async getUrlSuffixes(storeCode: string): Promise<UrlSuffixes>

The store's product / category URL suffixes, defaulting to Magento's ".html" when the config cannot be read. Store config, so cached long.

resolveRoute function

async resolveRoute(storeCode: string, url: string): Promise<RouteResolution | null>

Resolve a Magento request path through its url_rewrite table (stock route query). Null when nothing matches. Cached per store + path, and the miss is cached too, so a crawler replaying dead URLs costs Magento one lookup per path per TTL.

@magenxcommerce/engine/magento/gdpr

packages/engine/src/magento/gdpr.ts

getGdprCookieGroups function

async getGdprCookieGroups(storeCode: string): Promise<GdprCookieGroup[]>

Fetches the store's cookie registry (categories + declared cookies) for the cookie policy page. Public, store-wide data - same answer for every visitor of a given store - so it is cached like getClientStoreConfig. Server-side only: this is never called from the client, so it stays out of the persisted-query allowlist by design.

@magenxcommerce/engine/magento/store

packages/engine/src/magento/store.ts

getClientStoreConfig function

async getClientStoreConfig(storeCode: string): Promise<StoreConfig | null>

Fetch the broad GetStoreConfig payload (reward-points / gift-message / product-alert / order-cancellation / best-seller flags) that several client components previously each fetched themselves via useQuery(GET_STORE_CONFIG) — one network round-trip per component per page load.

These are all static-per-store-view admin settings, so we fetch them ONCE on the server (cached, tag-invalidated) and hand the result to <StoreConfigProvider>; the client components then read it from React context with zero client GraphQL. The server header reads store_name from the same cached entry, so one Magento call serves both. Invalidate via /api/revalidate with the store-config:${storeCode} tag. Fails soft to null so a cold/erroring config never breaks a page.

getStorePickupLocations function

async getStorePickupLocations(storeCode: string): Promise<ReadonlyArray<StorePickupLocation>>

Fetch the merchant's in-store pickup locations (Magenx_StorePickupGraphQl) for storeCode. Used server-side by the Contact-page store locator; the checkout picker fetches the same op client-side. Static-per-store-view admin config, so cached per storeCode under the store-config tag (invalidate via /api/revalidate). Returns [] when the feature is disabled or on error, so the Contact page simply omits the locator.

getGaranNotice function

async getGaranNotice(storeCode: string): Promise<GaranNotice | null>

Fetch the EU harmonised legal guarantee notice (Magenx_GaranGraphQl) for storeCode. Static-per-store-view admin config, so cached per storeCode under the store-config tag like the store config itself. Returns null when the notice is disabled, the module is not deployed, or on error — every consumer then renders nothing.