GraphQL client, operations, fragments, and code generation for WooGraphQL Next storefronts
The graphql/ directory contains the GraphQL client, operations, fragments, and generated types that power all data fetching in the storefront. Files are generated based on your configuration (product types, auth type, NextPress, checkout, account pages).
| File | Description |
|---|---|
client.ts | GraphQL client setup, SDK factory, and server-side fetch helpers |
common.ts | TypeScript utility types derived from generated GraphQL types |
index.ts | Barrel export for generated, client, and common |
fragments.graphql | Reusable GraphQL fragments for products, cart, orders, customers |
operations.graphql | All queries and mutations |
generated.ts | Auto-generated types and SDK (output of codegen -- do not edit) |
The client uses graphql-request and is configured in client.ts:
import { GraphQLClient } from 'graphql-request'; export function getClient() { const endpoint = process.env.GRAPHQL_ENDPOINT; if (!endpoint) { throw new Error('GRAPHQL_ENDPOINT is not defined'); } return new GraphQLClient(endpoint); } export function getClientWithSdk() { return getSdk(getClient()); }
getClient() returns a raw GraphQLClient for cases where you need to set custom headers (auth tokens, session tokens). getClientWithSdk() returns the typed SDK generated by codegen for convenient, type-safe queries.
client.ts also exports helper functions that call the Next.js API routes with built-in caching:
| Function | Description |
|---|---|
fetchProducts(variables?) | Fetch paginated product listings (24h cache) |
fetchProductsCount(where) | Get total product count for a filter |
fetchCollectionStats(where, taxonomies) | Fetch collection filter stats (price ranges, attribute counts) |
fetchCategories(pageSize, pageLimit?, where?) | Fetch all product categories with auto-pagination |
fetchProduct(id, idType) | Fetch a single product (24h cache) |
When credentialStorageType = cookies, additional helpers are generated:
| Function | Condition | Description |
|---|---|---|
fetchSessionData() | cookies | Fetch customer and cart with cookie forwarding |
fetchAssetsByUri(uri) | cookies + NextPress | Fetch WordPress scripts/stylesheets for a page |
fetchPageWithSession(uri) | cookies + NextPress | Fetch WordPress page content with session |
fetchCartPage() | cookies + NextPress | Fetch cart page content |
fetchCheckoutPage() | cookies + NextPress | Fetch checkout page content |
fetchOrder(orderId, key) | cookies + NextPress | Fetch order details |
fragments.graphql defines reusable fragments that are composed across queries and mutations. The fragments adapt based on your configuration:
| Fragment | On Type | Description |
|---|---|---|
ThumbnailImageFields | MediaItem | Thumbnail-sized image (WooCommerce thumbnail) |
ImageFields | MediaItem | Full-size image |
ProductContentSlice | ProductUnion | Minimal product data for listings (id, name, price, stock) |
ProductContentSmall | ProductUnion | Extended listing data (short description, raw price, on sale) |
ProductTaxonomies | Product | Product categories and tags |
VariationContent | ProductVariation | Variation fields including attributes |
ProductContentFull | Product | Complete product data for detail pages |
CartItemContent | CartItem | Cart line item with product and variation |
CartContent | Cart | Full cart with items, coupons, shipping, totals |
LineItemFields | LineItem | Order line item |
AddressFields | CustomerAddress | Billing/shipping address fields |
OrderFields | Order | Complete order data |
CustomerFields | Customer | Customer profile, orders, addresses |
| Fragment | Condition | Description |
|---|---|---|
SubscriptionFields | subscription product type | Subscription billing details |
PaymentTokenFields | account pages | Payment method tokens |
PaymentTokenCCFields | account pages | Credit card token details |
PaymentTokenECheckFields | account pages | eCheck token details |
UriAssetFields | NextPress | WordPress enqueued scripts and stylesheets |
operations.graphql defines all queries and mutations. Like fragments, operations are conditionally included based on configuration.
| Operation | Description |
|---|---|
GetProducts | Paginated product listing with filters |
GetProduct | Single product by ID |
GetProductVariation | Single variation by ID |
GetProductsCount | Product count for filter conditions |
GetCollectionStats | Filter stats (price range, attribute counts) |
GetShopCategories | Paginated product categories |
GetShopTags | Paginated product tags |
GetSession | Current cart and customer data |
GetCountries | WooCommerce allowed countries |
GetCountryStates | States/provinces for a country |
GetCart | Cart contents with optional recalculation |
| Operation | Condition | Description |
|---|---|---|
AddToCart | - | Add simple/variable product to cart |
AddCompositeToCart | composite type | Add composite product to cart |
AddBundleToCart | bundle type | Add bundle product to cart |
UpdateCartItemQuantities | - | Update cart item quantities |
RemoveItemsFromCart | - | Remove items from cart |
Login | withAuth | Authenticate and get tokens |
RefreshAuthToken | withAuth | Refresh an expired auth token |
Register | withAuth | Register a new customer |
UpdateCustomer | - | Update customer profile |
UpdateSession | - | Update session data |
ApplyCoupon | - | Apply coupon code to cart |
RemoveCoupons | - | Remove coupon codes |
UpdateShippingMethod | - | Change selected shipping method |
EmptyCart | - | Clear all items from cart |
CreateOrder | checkout | Create an order from the cart |
WriteProductReview | - | Submit a product review |
SetDefaultPaymentMethod | account pages | Set default saved payment method |
DeletePaymentMethod | account pages | Delete a saved payment method |
CancelSubscription | subscription type | Cancel a subscription |
ReactivateSubscription | subscription type | Reactivate a cancelled subscription |
| Operation | Condition | Description |
|---|---|---|
FetchContentByUri | NextPress | Fetch WordPress page/post content |
FetchAssetsByUri | NextPress | Fetch enqueued scripts/stylesheets |
FetchOrder | NextPress | Fetch order by database ID |
common.ts exports utility types derived from the generated GraphQL types:
// Product union type from GetProductQuery type ProductQueryResult = NonNullable<GetProductQuery['product']>; // Extract specific product type by __typename type ProductOf<T extends ProductQueryResult['__typename']> = Extract<ProductQueryResult, Partial<{ __typename: T }>>; // Specific product result types type SimpleProductResult = ...; type VariableProductResult = ...; type ExternalProductResult = ...; // if external type enabled type BundleProductResult = ...; // if bundle type enabled type CompositeProductResult = ...; // if composite type enabled type GroupedProductResult = ...; // if grouped type enabled // Listing product node type type ProductsQueryNode = ...; // Session types type SessionCart = NonNullable<GetSessionQuery['cart']>; type SessionCustomer = NonNullable<GetSessionQuery['customer']>;
These types are used throughout the storefront components to ensure type safety without importing from the generated file directly.
The codegen configuration file uses @woographql/codegen presets:
import { disableEsLint, defaultPlugins, defaultPluginsConfig } from '@woographql/codegen'; export const Config = { schema: [process.env.GRAPHQL_ENDPOINT], verbose: true, overwrite: true, generates: { 'src/graphql/generated.ts': { documents: ['src/graphql/**/*.graphql'], plugins: [disableEsLint(), ...defaultPlugins, 'typescript-graphql-request'], config: defaultPluginsConfig, }, }, };
The codegen reads your .env for the GRAPHQL_ENDPOINT, introspects the WPGraphQL schema, and generates TypeScript types plus a typed SDK from your .graphql files.
npx woonext codegen
Or with watch mode during development:
npx woonext codegen --watch
The generated generated.ts file should not be edited manually. Modify the .graphql files and re-run codegen to update types.