---
title: "Use GraphQL to fetch component-level data in JSS Next.js apps"
slug: "use-graphql-to-fetch-component-level-data-in-jss-next-js-apps"
abstract: "Example of fetching data with GraphQL in components"
---
# Use GraphQL to fetch component-level data in JSS Next.js apps

The Next.js sample app supports two methods for [component-level data fetching](https://doc.sitecore.com/sai/en/developers/jss/215/jss-sai/component-level-data-fetching-in-jss-next-js-apps.html "Component-level data fetching in JSS Next.js apps") with GraphQL:

- [Connected GraphQL](https://doc.sitecore.com/sai/en/developers/jss/215/jss-sai/use-graphql-to-fetch-component-level-data-in-jss-next-js-apps.html#UUID-6c1a5700-bad9-3412-3f60-531c79a560d6_section-idm234605721687308 "Component-level data fetching with connected GraphQL"), which enables you to query GraphQL endpoints from your component code.
- [Integrated GraphQL](https://doc.sitecore.com/sai/en/developers/jss/215/jss-sai/use-graphql-to-fetch-component-level-data-in-jss-next-js-apps.html#UUID-6c1a5700-bad9-3412-3f60-531c79a560d6_section-idm1853460572162122 "Component-level data fetching with integrated GraphQL") (IGQL), which involves adding queries to rendering items in SitecoreAI.

> [!warning]
> **Danger**
> Do not include secrets or sensitive information in component-level `getStaticProps` and `getServerSideProps` functions. These functions are included in the client-side bundle. Also included in the client bundle are any imports the functions depend on, even if the client-side code does not use the imports.
>
> This does not affect page-level `getStaticProps` and `getServerSideProps` functions.

## Component-level data fetching with connected GraphQL

The sample app provides a GraphiQL interface for exploring the schema and testing queries. By default, the interface can be accessed using `${SITECORE_API_HOST}/sitecore/api/graph/edge/ui?sc_apikey=${SITECORE_API_KEY}`. This interface is helpful if you want to determine what GraphQL types can be used by your components.

> [!note]
> The `graphql-let` library provides the same information about types in the corresponding `.graphq.d.ts` files.

To use component-level data fetching with connected GraphQL:

1. In a `GraphQL-ConnectedDemo.dynamic.graphql` file, define a GraphQL query. For example:

    ```graphql
    query ConnectedDemoQuery($datasource: String!, $contextItem: String!, $language: String!) {
      # Datasource query
      # $datasource should be set to the ID of the rendering's datasource item
      datasource: item(path: $datasource, language: $language) {
        id
        name
        # Strongly-typed querying on known templates is possible!
        ...on GraphQLConnectedDemo {
          # Single-line text field
          sample1 {
            # the 'jsonValue' field is a JSON blob that represents the object that
            # should be passed to JSS field rendering helpers (i.e. text, image, link)
            jsonValue
            value
          }
          # General Link field
          sample2 {
            jsonValue
            # Structured querying of the field's values is possible
            text
            target
            url
            # Access to the template definition is possible
            definition {
              type
              shared
            }
          }
        }
      }

      # Context/route item query
      # $contextItem should be set to the ID of the current context item (the route item)
      contextItem: item(path: $contextItem, language: $language) {
        id
        # Get the page title from the app route template
        ...on AppRoute {
          pageTitle {
            value
          }
        }

        # List the children of the current route
        children(hasLayout: true) {
          results {
            id
            # typing fragments can be used anywhere!
            # so in this case, we're grabbing the 'pageTitle'
            # field on all child route items.
            ...on AppRoute {
              pageTitle {
                jsonValue
                value
              }
            }
            url{
              path
            }
          }
        }
      }
    }
    ```

    The library `graphql-let` generates a file `GraphQLDemoQuery.graphql.d.ts`.

2. In your component file, add the following import statements:

    ```typescript
    import React, { useEffect } from 'react';
    import {
      Text,
      Link,
      GetServerSideComponentProps,
      GetStaticComponentProps,
      constants,
      GraphQLRequestClient,
      withDatasourceCheck,
    } from '@sitecore-jss/sitecore-jss-nextjs';
    import {
      resetEditorChromes
    } from '@sitecore-jss/sitecore-jss-nextjs/utils';
    import { ComponentProps } from 'lib/component-props';
    import config from 'temp/config';
    ```

3. If needed, [update your introspection data](https://doc.sitecore.com/sai/en/developers/jss/215/jss-sai/introspecting-the-graphql-schema-in-jss-next-js-apps.html#UUID-857c84c7-2446-4bc8-670b-2f6cd7106e78_section-idm452594043420323242848070384 "Update introspection data") to have access to the latest GraphQL types.
4. Import your GraphQL query and GraphQL types:

    ```typescript
    import { ConnectedDemoQueryDocument } from './GraphQL-ConnectedDemo.dynamic.graphql';
    import {
      AppRoute as AppRoute,
      Item,
      GraphQlConnectedDemo as GrapQLConnectedDemoDatasource,
    } from 'graphql-types';
    ```

5. Define your TypeScript types and the `GraphQLDemo` component:

    ```csharp
    type RouteItem = AppRoute & Item;

    type GraphQLConnectedDemoData = {
      datasource: GrapQLConnectedDemoDatasource;
      contextItem: RouteItem;
    };

    type GraphQLConnectedDemoProps = ComponentProps & GraphQLConnectedDemoData;

    const GraphQLConnectedDemo = (props: GraphQLConnectedDemoProps): JSX.Element => {
      useEffect(() => {
        resetEditorChromes();
      }, []);

      return (
        // your markup
      );
    };
    ```

6. In your component, define `getStaticProps` or `getServerSideProps` functions. The following example implements the `getStaticProps` function. Because GraphQL does not work in disconnected mode, you must exit the function if the app runs in disconnected mode. You must also create a new GraphQL client using the `GraphQLRequestClient` class. For example:

    ```typescript
    export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData) => {
      if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
        return null;
      }
      const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, {
        apiKey: config.sitecoreApiKey,
      });
    }
    ```

7. Perform the request and return the result:

    ```typescript
    export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData) => {
      if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
        return null;
      }
      const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, {
        apiKey: config.sitecoreApiKey,
      });
      const result = await graphQLClient.request<GraphQLConnectedDemoData>(
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ConnectedDemoQueryDocument as any,
        {
          datasource: rendering.dataSource,
          contextItem: layoutData?.sitecore?.route?.itemId,
          language: layoutData?.sitecore?.context?.language,
        }
      );
      return result;
    };
    ```

8. Export your component, wrapped in the `withDatasourceCheck` higher-order component:

    ```tsx
    export default withDatasourceCheck()<ComponentProps>(GraphQLConnectedDemo);
    ```

To help make sure you've configured your application correctly, you can compare it to the [connected GraphQL component included in the Sitecore sample app](https://github.com/Sitecore/jss/blob/release/21.0.0/packages/create-sitecore-jss/src/templates/nextjs-styleguide/src/components/graphql/GraphQL-ConnectedDemo.dynamic.tsx).

> [!tip]
> If you're building a very large website using SitecoreAI, you might have to [enable retries for requests to the SitecoreAI Experience Edge GraphQL endpoint](https://doc.sitecore.com/sai/en/developers/jss/215/jss-sai/enable-retries-for-requests-to-the-sitecoreai-experience-edge-graphql-endpoint.html "Enable retries for requests to the SitecoreAI Experience Edge GraphQL endpoint") for the build process to complete.

## Component-level data fetching with integrated GraphQL

[Integrated GraphQL (IGQL)](https://doc.sitecore.com/sai/en/developers/jss/215/jss-sai/integrated-graphql-in-jss-apps.html "Integrated GraphQL in JSS apps") directly affects the layout data shape returned for a specific component by the Experience Edge layout response.

A GraphQL query can be defined on the rendering item that shapes the data returned by the layout service, and can be used from the `props.fields` object in the same way as a standard response. This gives you more control over the shape of the data being returned.

To add IGQL to a component, you can enter the query in the `Component GraphQL Query` field on the rendering item of the component.

![The Component GraphQL Query field, containing an integrated GraphQL query.](https://doc.sitecore.com/api/markdown-image/sai/en/developers/jss/215/jss-sai/images/integrated-component-graphql-query.png)

> [!tip]
> Refer to the following sources for more information:
>
> -   [Integrated GraphQL component in the Sitecore sample app](https://github.com/Sitecore/jss/blob/release/21.0.0/packages/create-sitecore-jss/src/templates/nextjs-styleguide/src/components/graphql/GraphQL-IntegratedDemo.tsx) - for configuration and implementation guidance.
>
> -   [Integrated GraphQL in JSS apps](https://doc.sitecore.com/sai/en/developers/jss/22/jss-sai/integrated-graphql-in-jss-apps.html) - for recommendations on when to use Integrated GraphQL and when to avoid it.