---
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: "How to use two different GraphQL methods (connected or integrated) to fetch data with 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/xp/en/developers/hd/23/sitecore-headless-development/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/xp/en/developers/hd/23/sitecore-headless-development/use-graphql-to-fetch-component-level-data-in-jss-next-js-apps.html#UUID-26ae6175-2c4b-c24f-5cf5-83ea40780a45_section-idm234604415675995 "Component-level data fetching with connected GraphQL"), which enables you to query GraphQL endpoints from your component code. Following the [code-first developer workflow](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/code-first-development-workflow.html "Code-first development workflow"), you can do this only in [connected mode](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/start-a-jss-app-in-connected-mode.html "Start a JSS app in connected mode").
- [Integrated GraphQL](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/use-graphql-to-fetch-component-level-data-in-jss-next-js-apps.html#UUID-26ae6175-2c4b-c24f-5cf5-83ea40780a45_section-idm1853460441488278 "Component-level data fetching with integrated GraphQL") (IGQL), which involves adding queries to rendering items in Sitecore.

> [!note]
> If you include secrets or sensitive information in component-level `getStaticProps` and `getServerSideProps` functions, that information will only be included in the client-side bundle in development mode.

## Component-level data fetching with connected GraphQL

In the code, it is a good practice to have strong types connected to GraphQL types defined in the Sitecore GraphQL Edge endpoint. The application uses the library `graphql-let` and [GraphQL introspection data](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/introspecting-the-graphql-schema-in-jss-next-js-apps.html "Introspecting the GraphQL schema in JSS Next.js apps") to achieve this.

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.graphql` file, define a GraphQL query following the *Connected Demo* query example.

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

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

    ```typescript
    import {
      constants,
      GetServerSideComponentProps,
      GetStaticComponentProps,
      useComponentProps,
    } from '@sitecore-jss/sitecore-jss-nextjs';
    import { GraphQLRequestClient } from '@sitecore-jss/sitecore-jss-nextjs/graphql';
    ```

3. If needed, [update your introspection data](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/introspecting-the-graphql-schema-in-jss-next-js-apps.html#UUID-f97fca1b-aa36-845e-8191-a6c9e8b81963_section-idm452594043420323242848070384 "Update introspection data") to have access to the latest GraphQL types.
4. Import your GraphQL query:

    ```typescript
    import {
      ConnectedDemoQueryDocument,
      AppRoute,
      Item,
      GraphQlConnectedDemo as GrapQLConnectedDemoDatasource,} from './ConnectedDemoQuery.graphql';
    ```

5. In your component, define `getStaticProps` or `getServerSideProps` functions. In this example, we implement `getStaticProps`. 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 `graphqlClientFactory` property from `lib/graphql-client-factory`. For example:

    ```typescript
    import graphqlClientFactory from 'lib/graphql-client-factory';
    ...
    export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData) => {
      if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
        return null;
      }
      const graphQLClient = graphqlClientFactory();
    }
    ```

6. Perform the request and return the result:

    ```typescript
    import graphqlClientFactory from 'lib/graphql-client-factory';
    ...
    export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData) => {
      if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
        return null;
      }
      const graphQLClient = graphqlClientFactory();
      const result = await graphQLClient.request<GraphQLConnectedDemoData>(MyQuery, {
        datasource: rendering.dataSource,
        contextItem: layoutData?.sitecore?.route?.itemId,
        language: layoutData?.sitecore?.context?.language,
      });
      return result;
    };
    ```

7. In your component function, you can access the resulting data using the `useComponentProps` hook:

    ```typescript
    const GraphQLConnectedDemo = (props: StyleguideComponentProps): JSX.Element => {
      const data = useComponentProps<GraphQLConnectedDemoData>(props.rendering.uid);
      // implement your component
    }
    ```

8. Implement a strategy for showing content in editing mode. You can use the Sitecore context to render static data. Alternatively, to see `master` database data in editing mode, instantiate the GraphQL client with the endpoint URL for the Content Management instance.

    > [!note]
    > If you omit this step, the application displays the same data in editing mode as it does for site visitors because the Content Delivery URL endpoint serves from the `web` rather than the `master` database.

    - To render placeholder markup in your component:

        ```typescript
        import { useSitecoreContext} from '@sitecore-jss/sitecore-jss-nextjs';

        const MyComponent = () => {
          const { sitecoreContext } = useSitecoreContext();
          // define some stub data
          if (sitecoreContext.pageEditing) {
            return (
              <div>
               This would usually render dynamic GraphQL data. This stub is used only for editing mode.
              </div>
            );
          }
          // ... rest of the component
        }
        ```

    - To use a different endpoint for data fetching, check if the component is in preview/edit mode and switch the URL accordingly. In this example, we assume you assigned your GraphQL editing URL to an environment variable named `EDITING_GQL_ENDPOINT`.

        ```typescript
        export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData, context) => {

          if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
            return null;
          }

          const {preview} = context;
          const graphQLEndpoint = preview ? process.env.EDITING_GQL_ENDPOINT : config.graphQLEndpoint;

          // if using getServerSideProps, you can use the Sitecore context from the layoutData
          // const graphQLEndpoint = layoutData.sitecore.context.pageEditing ? process.env.EDITING_GQL_ENDPOINT : config.graphQLEndpoint;

          const graphQLClient = new GraphQLRequestClient(graphQLEndpoint, {
            apiKey: config.sitecoreApiKey,
          });

          const result = await graphQLClient.request<GraphQLConnectedDemoData>(MyQuery, {
            datasource: rendering.dataSource,
            contextItem: layoutData?.sitecore?.route?.itemId,
            language: layoutData?.sitecore?.context?.language,
          });

          return result;
        };
        ```

        > [!note]
        > The `sitecoreApiKey` can differ between endpoints so make sure you switch it using a logic similar to switching the endpoint.

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).

For a more complex example of using GraphQL queries in components, in the `nextjs-styleguide` addon template, see the component defined in the `/src/components/graphql/GraphQL-ConnectedDemo.dynamic.tsx`.

## Component-level data fetching with integrated GraphQL

[Integrated GraphQL (IGQL)](https://doc.sitecore.com/xp/en/developers/hd/23/sitecore-headless-development/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/xp/en/developers/hd/23/sitecore-headless-development/images/integrated-component-graphql-query.png)

> [!tip]
> Refer to the [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 guidance if needed.