Calling GraphQL from the Frontend

Send GraphQL requests with fetch, build a reusable request helper, and handle response data and errors correctly.

🎯 Introduction

The previous five articles focused on the server: defining schemas, writing resolvers, and integrating Express. One piece remains: using those APIs from a frontend page.

In this article, you will see how a GraphQL request can be sent as a POST request, build a reusable helper with the browser's built-in fetch, query and render data in Vue 3, and handle response errors. This completes the flow from the browser to the GraphQL service.


🧱 What a GraphQL Request Looks Like

Despite its distinctive query syntax, sending a GraphQL request over the network can be as simple as an ordinary POST request:

  • URL: the service endpoint, such as http://localhost:4000/graphql.
  • Header: Content-Type: application/json.
  • Body: JSON containing query (the operation document) and optionally variables.

First, use curl to request the user list from our service:

curl http://localhost:4000/graphql \
    -H 'Content-Type: application/json' \
    -d '{"query":"{ users { username age } }"}'

Response:

{
    "data": {
        "users": [
            { "username": "Alex", "age": 20 },
            { "username": "Emma", "age": 22 }
        ]
    }
}

Once you understand this, frontend requests are straightforward. No specialized library is required; fetch is enough.

If the frontend and GraphQL service use different ports, such as 3000 and 4000, the browser treats requests as cross-origin. Standalone mode allows cross-origin requests by default. With Express integration, add cors middleware to the /graphql route.

🛠 Building a Request Helper with fetch

Start by wrapping GraphQL requests in a reusable function, so application code only needs to provide the operation document and variables:

api.js
const API_URL = 'http://localhost:4000/graphql';

export async function graphqlRequest(query, variables) {
    const res = await fetch(API_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ query, variables }),
    });

    const result = await res.json();

    if (result.errors) {
        throw new Error(result.errors[0].message);
    }

    return result.data;
}

This helper sends a POST request in the required format, parses the JSON response, and throws GraphQL errors as JavaScript exceptions. Any page can then request data with one call:

const data = await graphqlRequest('{ users { username age } }');
console.log(data.users);

✨ Using the Helper in Vue 3

Here is a complete small page: load and render the user list when the page mounts, then reload it after a button creates a user.

UserList.vue
<script setup>
import { ref, onMounted } from 'vue';
import { graphqlRequest } from './api';

const users = ref([]);

async function loadUsers() {
    const data = await graphqlRequest(`
        {
            users {
                id
                username
                age
            }
        }
    `);
    users.value = data.users;
}

async function addUser() {
    await graphqlRequest(
        `
            mutation Create($input: CreateUserInput!) {
                createUser(input: $input) {
                    id
                }
            }
        `,
        {
            input: { username: 'New user', age: 18 },
        }
    );
    await loadUsers();
}

onMounted(() => {
    loadUsers();
});
</script>

<template>
    <ul>
        <li v-for="item in users" :key="item.id">
            {{ item.username }}({{ item.age }} years old)
        </li>
    </ul>
    <button @click="addUser">Add user</button>
</template>

Notice how addUser keeps the operation document fixed and passes dynamic values through variables. This puts the variable mechanism from the third article into practice. Reads and writes use the same helper; the operation document simply uses mutation for writes.


💡 Error Handling and Choosing a Client

GraphQL error handling has an important characteristic: application errors do not always produce HTTP error status codes.

For example, requesting an unknown field may produce an HTTP 200 response in some setups, with an errors array instead of data:

{
    "errors": [
        { "message": "Cannot query field \"hobbies\" on type \"User\"." }
    ]
}

Another common case is partial success: the user list loads, but resolving one field fails. The response then contains both data and errors. Clients should therefore check the response body's errors field, rather than relying only on HTTP status codes. Our graphqlRequest helper does this.

For everyday projects, consider these options:

  • Use fetch directly: a small helper like this has no dependencies and is sufficient for many small and medium projects.
  • Apollo Client: a dedicated GraphQL client with caching and loading-state management. Consider it for projects with many queries or caching requirements. Vue integrations provide composables for using it.

Start with fetch to understand the request flow. You can introduce a dedicated client when you need features such as caching.


❓ Questions and Answers

Q1: Can GraphQL use GET requests?

Yes. Queries can be sent with the query document in the URL, but POST is commonly used for consistency. Mutations must not use GET, and POST also avoids URL length limits.

Q2: Why not use axios?

You can. An axios POST request works with GraphQL too. This article uses fetch because it has no dependencies and is built into browsers and Node.js. If your project already uses axios, use it directly.

Q3: What if navigating between pages repeatedly requests the same data?

That is the caching problem clients such as Apollo Client address. With fetch, you can store query results in a simple key-value cache or manage data in Pinia, depending on your needs.

Q4: Can I omit variables?

Yes. If the operation does not use variables, call graphqlRequest(query) without a second argument. The variables property is undefined, so JSON.stringify omits it from the request body.

Q5: How do I include a token in request headers?

Add an Authorization field to the helper's headers and populate it with a token from localStorage or Pinia, just as you would for REST requests.


🧪 Exercises

Exercise 1: Use graphqlRequest to write a getUserById(id) function. Pass the ID through a variable and return a single user object.

api.js
export async function getUserById(id) {
    // Write your code here
}

Exercise 2: Add a Delete button to UserList.vue. Call the deleteUser mutation when clicked and refresh the list after successful deletion.

UserList.vue
<script setup>
async function removeUser(id) {
    // Write your code here
}
</script>

🎉 You now understand the complete flow from a frontend page to a GraphQL service! With schema design, queries, mutations, Express integration, and frontend requests covered, you have the tools to build complete GraphQL features. Try them in a real project!