Use GraphQL to fetch component-level data in a Next.js Content SDK app
The following example describes how to execute server-side GraphQL queries to get data and use it to populate components. Although this example does not use code generation to automatically create the required types of GraphQL queries and return objects, we strongly recommend introducing code generation in your own work flow.
-
Familiarize yourself with the best practices for working with GraphQL.
-
If you're building a very large website using SitecoreAI, you might need to enable retries for requests to the SitecoreAI Experience Edge GraphQL endpoint for the build process to complete.
To use GraphQL to fetch component-level data in a Next.js app:
-
In your component file, define a GraphQL query. For example:
-
Also in your component file, add the following import statements:
-
Define the types for the result of the GraphQL query. For example:
-
Define your TypeScript types and the
GraphQLDemocomponent: -
Define the
getComponentServerPropsfunction and initializeGraphQLRequestClient: -
Perform the request and return the result:
See The Sitecore configuration file for more information.
-
Export your component, wrapped in the
withDatasourceCheckhigher-order component:
Use the SitecoreClient's getData method
SitecoreClient's getData methodFor apps that use Content SDK 1.2 or later, the SitecoreClient API exposes a simple, typed way to run raw GraphQL requests. It forwards your call to the SDK’s low-level GraphQLClient.request with the same retry, header, and fetch behavior you’ve configured.
Given below is the type signature of the getData method:
The following example retrieves results (id and name) where the name equals Home and the language is en:
The following example uses the graphql-tag library to build the query and it retrieves results (id) where the language is en.