Architecture

GraphQL in Magento 2: Building a Custom Headless Frontend

13 min read·272 words
GraphQL in Magento 2: Building a Custom Headless Frontend

Magento's GraphQL API is powerful but has quirks. We walk through building a performant headless storefront — from schema exploration to optimistic UI and caching.

Magento's GraphQL API has matured significantly since its introduction in 2.3. It now covers products, catalog, search, cart, checkout, customer accounts, and orders. Building a headless storefront on top of it requires understanding its quirks and knowing where to fill the gaps with custom resolvers.

Schema Exploration and Key Queries

Use GraphiQL or Altair to explore the schema at your store's /graphql endpoint. Key queries to understand: products (catalog search with filters), cart operations (createEmptyCart, addProductsToCart, placeOrder), and customer (authentication via generateCustomerToken). The schema is large — start by mapping only the queries your UI actually needs.

Extending the Schema

When you need data that isn't in the default schema, create a custom GraphQL module. Define your type in schema.graphqls, implement the resolver class, and Magento will merge it into the main schema. Common extensions: adding store-specific metadata, exposing custom product attributes, and surfacing custom pricing rules.

Client-Side Caching Strategy

Use Apollo Client or urql on the frontend. Configure normalized caching keyed on product ID and SKU so product data fetched in a listing page reuses the same cache entry as the product detail page. Persist the cache to localStorage for instant page loads on repeat visits. Implement optimistic updates for cart operations — the UI updates immediately while the network request processes in the background.

Handling Authentication

Magento uses JWT tokens for customer authentication. generateCustomerToken returns a short-lived token; store it in httpOnly cookies (not localStorage) to prevent XSS. Implement token refresh on 401 responses using Apollo's error link. Guest cart sessions are managed via a guest cart token — merge guest cart with customer cart on login using mergeCarts mutation.

# magento# ecommerce# adobe-commerce# architecture# headless-commerce# graphql# api-design# pwa