> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://contentful.com/developers/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://contentful.com/developers/docs/_mcp/server.

# Using Contentful GraphQL with JavaScript

> This guide shows you how to use Apollo Client with GraphQL from Contentful while using a front-end JavaScript framework.

> **Info**
>
> **Disclaimer**: GraphQL Content API is available on all spaces for customers on [current pricing plans](https://www.contentful.com/pricing/). If you are on a legacy plan, contact [Customer Support](https://www.contentful.com/support/) to upgrade.

In order to pull content from the new [Contentful GraphQL endpoint](/tutorials/general/graphql) using JavaScript, you don't require any additional tools or specific clients. You can execute queries to the GraphQL API over HTTP in the developer console of your browser, or using cURL, with the query as a hardcoded string. However, in many client-side applications, it is preferable to use a GraphQL client that provides caching, pre-fetching, and other advanced features. [Apollo Client](https://www.apollographql.com/blog/announcement/frontend/zero-config-graphql-state-management/#advanced-migration) is one of the most popular and well supported GraphQL clients. It is being used by Contentful to create the [GraphQL Example App in JavaScript](https://the-example-app-graphql-js.netlify.com/). Apollo Client supports many platforms and the example app is built on React.

## Log Request ID

When submitting support tickets, include the request ID along with other logs. Providing the request ID ensures faster and more effective responses to your inquiries.
You can find it in the response header under `x-contentful-request-id`.

### Get request ID from Apollo Client

Use the following code snippet to access response headers (request ID) from Apollo Client.

```javascript
import {
    ApolloLink
} from 'apollo-link';
import {
    createHttpLink
} from 'apollo-link-http';

const httpLink = createHttpLink({
    uri: 'http://localhost:3001/graphql'
});

const afterwareLink = new ApolloLink((operation, forward) => {
    return forward(operation).map(response => {
        const context = operation.getContext();
        const {
            response: {
                headers
            }
        } = context;

        if (headers) {
            const requestId = headers.get("X-Contentful-Request-Id");

            if (requestId) {
                console.log("requestId", requestId);
            }

        }
        return response;
    });
});

// use with apollo-client
const link = afterwareLink.concat(httpLink);
```

## Overview

The workflow when working with the GraphQL API, Apollo Client, and a front-end JavaScript framework is as follows:

1. Write and test your queries using GraphiQL or your preferred GraphQL playground tool.
2. Integrate Apollo Client (and view-layer integrations) into your application.
3. Use queries from GraphiQL in your application; write logic for handling responses.
4. \[Optional] Setup IntrospectionFragmentMatcher and replace ApolloBoost client with ApolloClient client.

## Write your GraphQL queries

Use a GraphQL playground, such as GraphiQL to test your GraphQL queries and get to know the schema. Contentful provides a GraphiQL interface to test queries in the browser at

`https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}/explore?access_token={CDA_TOKEN}`

## Integrate Apollo Client into your application

Follow the Apollo Client [Getting Started Guide](https://www.apollographql.com/docs/react/get-started/) to install and integrate the client into your app. This guide is for React, but most of the steps are relevant for any frontend framework.

## Use queries from GraphiQL in your application

Use your already-written queries and write code to handle responses.

```javascript
import React from 'react';
import gql from 'graphql-tag';
import {
    Query
} from 'react-apollo';
// You can import queries and fragments from a schema file
import {
    lessonFragment
} from '../schema';
import {
    Loading,
    Error
} from './LoadingStates';
import Course from './Course';

// You can also define queries directly in your React file
const courseFragment = gql`
  fragment CourseFragment on Course {
    slug
    title
    shortDescription
    description
    duration
    skillLevel
    lessonsCollection {
      items {
        ...LessonFragment
      }
    }
  }
  ${lessonFragment}
`;

const courseBySlug = gql`
  query CourseBySlug($slug: String!) {
    courseCollection(where: { slug: $slug }) {
      items {
        ...CourseFragment
      }
    }
  }
  ${courseFragment}
`;

const CourseOverview = (props) => {
    const {
        'course-slug': slug,
        'lesson-slug': lessonSlug
    } = props;
    return ( <
        Query query = {
            courseBySlug
        }
        variables = {
            {
                slug
            }
        } > {
            ({
                loading,
                error,
                data
            }) => {
                if (loading) return <Loading / > ;
                if (error || data.courseCollection.items.length < 1) {
                    return <Error / > ;
                }
                const course = data.courseCollection.items[0];
                return <Course course = {
                    course
                }
                lessonSlug = {
                    lessonSlug
                }
                />;
            }
        } <
        /Query>
    );
};
```

## \[Optional] Setup `IntrospectionFragmentMatcher` & replace ApolloBoost client with ApolloClient client

*You may have encountered an error from Apollo Client if your client needs to use an `IntrospectionFragmentMatcher` instead of the default `HeuristicFragmentMatcher` . If you successfully executed your queries without seeing a related error, you can safely skip this step.*

Depending on your content model and queries, you might need to configure Apollo Client to use an `IntrospectionFragmentMatcher` instead of the default `HeuristicFragmentMatcher` to match fragments in the cache.

If any of your content types have one-to-many relationships, the generated GraphQL schema represents these with Union types. If your queries use fragments on one of these union types, Apollo Client cache needs to know a bit more about your schema in order to properly match fragments. You can read more about GraphQL schema generation in the GraphQL API Reference [here](/references/graphql/schema-generation#one-to-one-multi-type-relationships) and more about fragment matching in the Apollo Docs [here](https://www.apollographql.com/docs/react/advanced/fragments.html).

If you need to configure an `IntrospectionFragmentMatcher` , complete the following:

1. Replace ApolloBoost client with ApolloClient client.

   * ApolloBoost is often recommended as the fastest way to setup an Apollo client. In order to setup the `IntrospectionFragmentMatcher` , you need to configure your client manually. First [migrate from ApolloBoost to ApolloClient](https://www.apollographql.com/docs/react/advanced/boost-migration.html). Once this is completed, you can safely uninstall ApolloBoost from your project.

2. Introspect your schema and setup the `IntrospectionFragmentMatcher`

   * This requires writing a script to export parts of your schema as JSON and configuring your client to utilize it. Follow the guide [here](https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher). To keep this exported schema up-to-date with your current content model, it's recommended to include this script as part of your build process.

## Additional Resources:

* [The graphql js example app](https://github.com/contentful/the-example-app.graphql.js)
* [GraphQL Api Reference](/references/content-delivery-api/overview)