Nuxt GraphQL Client

0.2.46 · active · verified Tue Apr 21

nuxt-graphql-client is a comprehensive Nuxt 3 module designed to integrate GraphQL client capabilities with built-in code generation. Currently at version 0.2.46, the package sees frequent patch releases, indicating active development and responsiveness to bug fixes and minor feature enhancements. It leverages `graphql-request` for executing GraphQL operations and `graphql-code-generator` to automatically generate TypeScript types and composables (`useGql`, `useAsyncGql`, `Gql<OperationName>`) directly from your GraphQL schema and `.gql` files. This approach ensures full TypeScript support and Hot Module Reload (HMR) for GraphQL documents. Its key differentiators include a 'zero configuration' option for rapid setup, deep integration with the Nuxt 3 reactivity system and composables, and streamlined developer experience by automating boilerplate for GraphQL interactions, providing a modern alternative to more manually configured GraphQL client setups in Nuxt applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to configure the module, define a simple GraphQL query in a `.gql` file, and fetch data using the `useAsyncGql` composable within a Nuxt page, complete with loading and error states.

// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config';

export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],
  runtimeConfig: {
    public: {
      graphqlClient: {
        clients: {
          default: {
            host: process.env.NUXT_PUBLIC_GQL_HOST ?? 'https://graphqlzero.almansi.me/api' // Example host
          }
        }
      }
    }
  }
});

// graphql/GetUsers.gql (create this file in your project root or `server/` dir)
query GetUsers($options: PageQueryOptions) {
  users(options: $options) {
    data {
      id
      name
      email
    }
  }
}

// pages/index.vue
<template>
  <div>
    <h1>Users</h1>
    <p v-if="pending">Loading...</p>
    <p v-if="error">Error: {{ error?.message }}</p>
    <ul v-if="data?.users?.data">
      <li v-for="user in data.users.data" :key="user.id">{{ user.name }} ({{ user.email }})</li>
    </ul>
    <button @click="refresh">Refresh</button>
  </div>
</template>

<script setup lang="ts">
// Automatically generated function GqlGetUsers from graphql/GetUsers.gql
const { data, pending, error, refresh } = await useAsyncGql('GetUsers', {
  options: { paginate: { limit: 5 } }
});

// Example of setting an authentication token
// useGqlToken(process.env.NUXT_PUBLIC_AUTH_TOKEN ?? 'your-secret-token');
</script>

view raw JSON →