Do you need a GraphQL client for your frontend?
Tags: graphql, javascript, webdev
Published: 2022-01-25 15:32:54


If you are building out an application that will consume data through a GraphQL endpoint, you may be looking at different frontend GraphQL clients to bring into your project. You may be researching popular clients like GraphQL-Request or Apollo Client. But do you need these clients? **Do you need to add another dependency to your project because you want to use a GraphQL endpoint?**

Well, with many questions in software...it depends. Let’s break it down and look at what a GraphQL request actually is and other considerations. 

## **So what do you need to make a GraphQL request?**

**A GraphQL request is a standard POST request with a query as the body, sent to an endpoint**. That’s it - a POST request. 

The example below is a valid JavaScript fetch request. It sends a POST request with a query set to the body of our request. This returns the first 9 Pokémon. (Squirtle being the best one 🐢)

```jsx
fetch('https://beta.pokeapi.co/graphql/v1beta', {
    method: 'POST',
    body: JSON.stringify({
        query: `
            query samplePokeAPIquery {
            gen3_species: pokemon_v2_pokemonspecies(limit: 9, order_by: {id: asc}) {
                name
                id
            }
        }
      `,
    }),
})
    .then((res) => res.json())
    .then((result) => console.log(result));
```

*Did you know you can run JavaScript inside the Google Dev Tools Console? Press F12, go to the Console tab at the top, paste in the above code, press ENTER. And it will perform the request showing the data right there in the console.* 

![Using the Google Developer Console to make a GraphQL request](https://media.giphy.com/media/oVi87P4fhwVoPawjx5/giphy.gif)

It’s fairly common to see projects that consume a GraphQL endpoint to use something similar to what we see above. You would create a generic service that handles any of your authentication. Let your exposed service method take in the query string as an argument. And now you have a service that can make a GraphQL request to your endpoint. 

Find an example of this built out by Sitecore’s demo team here: [GitHub Repo](https://github.com/Sitecore/Sitecore.Demo.Edge/blob/309e8eac14764b5e83b27fbed62ef1f101adb8a8/tv/api/index.ts). They are querying the Experience Edge GraphQL endpoint using a simple fetch. 

**Bottom line: To request data from a GraphQL endpoint, all you need to do is make a POST request.** 

## Why would I want more? What does a dedicated client do for me?

More features (like caching) and ease of use come to mind first when considering using a GraphQL client. 

If you are considering the feature rich Apollo or Relay GraphQL client, then make sure their extensive suite of features are actually useful to you. Will having caching, fragments, co-location, and more help you? If you do not know what these features are then they may just add technical debt for you.

**The biggest reason I see for having using a GraphQL client is caching.** The Apollo client describes it's use case as: *"Use it to fetch, cache, and modify application data, all while automatically updating your UI."* ([Apollo Client Docs](https://www.apollographql.com/docs/react/)). So caching is the second mentioned feature of this particular client. 

The Apollo client uses **InMemoryCache** to create a client-side cache with the goal of reducing calls to your endpoint. Caching can take a number of different forms with GraphQL, so if you want to learn more I recommend this blog post: [GraphQL & Caching: The Elephant in the Room](https://www.apollographql.com/blog/backend/caching/graphql-caching-the-elephant-in-the-room/).

### What if you don't need caching? 

A lightweight client that I do often use is [GraphQL-Request](https://github.com/prisma-labs/graphql-request#features). It's lightweight enough for me, and adds readability and understandability to my code, but has no caching feature. Check out my comparison on [4 popular JavaScript GraphQL clients](https://thetombomb.com/posts/choosing-graphql-client) if you are interested in learning more. 

The below code sets up the GraphQL-Request client.

```tsx
// graphQLClient.ts
import { GraphQLClient } from "graphql-request";

const endpoint = process.env.PREVIEW_EDGE_CH_ENDPOINT as string;

const graphQLClient = new GraphQLClient(endpoint)
graphQLClient.setHeader('X-GQL-Token', process.env.PREVIEW_EDGE_CH_API_KEY as string)

export default graphQLClient;
```

Then I can easily make requests with this client anywhere in my app.

```tsx
// index.ts
import { GET_ALL_BLOGS } from '../graphQL/queries'
import graphQLClient from '../graphQL/graphQLClient'
  
const data = await graphQLClient.request(GET_ALL_BLOGS);
```

GraphQL-Request is a glorified POST request maker, but the simplicity of it and added readability to my code is worth the [18kb](https://bundlephobia.com/package/graphql-request@3.7.0) package size. 

## The Bottom Line About GraphQL Clients?

**Do you NEED to have a GraphQL client in order to make requests to a GraphQL Endpoint?** No. 

But they can be helpful for adding readability to your code. And some of the GraphQL clients like Apollo and Relay have a lot of helpful features. So it’s up to you to decide what features are important to you and your project.