Skip to main content

GraphQL queries

The gql function writes typed Storefront API queries, mutations, and fragments. TypeScript infers each operation's result and variables types without a codegen step.

Customer Account API documents use a separate gql function from @shopify/hydrogen/customer-account.

Import gql, InferResult, and InferVariables from @shopify/hydrogen.


Anchor to Typed queries and mutationsTyped queries and mutations

Writes a typed Storefront API query, mutation, or fragment. At runtime, the function returns the query text with each fragment appended once.

TypeScript infers the result and variables types from Hydrogen's bundled Storefront API schema, even when the client targets another apiVersion. Read the types with StorefrontApi.ResultOf and StorefrontApi.VariablesOf. To type a fragment on its own, compose the fragment into a query and read the type from the query. The FragmentOf helper from gql.tada doesn't accept gql documents.

Anchor to source
source
string
required

The Storefront API query, mutation, or fragment source text.

Anchor to fragments
fragments
readonly []

The gql fragments that the query text spreads.

A typed document to pass to the client's graphql() method.

Examples

TypeScript

import { gql, type StorefrontClient } from "@shopify/hydrogen";

const PRODUCT_QUERY = gql(`
query Product($handle: String!) {
product(handle: $handle) { title }
}
`);

export async function getProductTitle(storefront: StorefrontClient, handle: string) {
const result = await storefront.graphql(PRODUCT_QUERY, {
variables: { handle },
});

if (result.errors) return null;
return result.data.product?.title ?? null;
}

InferResult and InferVariables type a result or variables shape outside a GraphQL call, such as a function parameter or a loader argument. Pass the query text as a string literal type. For a gql document, use StorefrontApi.ResultOf and StorefrontApi.VariablesOf. InferResult and InferVariables resolve to never for a gql document.


Was this page helpful?