Nuxt GraphQL Client
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
-
Failed to load schema from X: Unable to merge GraphQL type "Y": Field "Z" already defined with a different type.
cause Conflicting type definitions when `graphql-code-generator` attempts to merge schemas from multiple configured GraphQL endpoints.fixEnsure that if multiple GraphQL schemas are being consumed, there are no naming conflicts for types or fields, or consider isolating clients to distinct type generation outputs. -
Nuxt instance unavailable error on the server-side.
cause Attempting to call Nuxt composables (like `useCookie`, `useState`) directly within the `gql:auth:init` hook during server-side rendering, where the Nuxt context is lost.fixRefactor your authentication plugin to ensure Nuxt composables are accessed before any `await` statements or before the `gql:auth:init` hook is executed. -
GQL_HOST environment variable is not defined
cause The GraphQL client host URL has not been provided in the Nuxt configuration or via an environment variable.fixSet the `NUXT_PUBLIC_GQL_HOST` environment variable or configure `runtimeConfig.public.graphqlClient.clients.default.host` in your `nuxt.config.ts` file. -
Unexpected token < in JSON at position 0
cause The GraphQL endpoint returned an HTML error page or another non-JSON response, which the client attempted to parse as JSON.fixVerify that your GraphQL API endpoint is correctly configured and returning valid JSON responses, especially for errors. Inspect the network response in developer tools to see the actual content returned by the server.
Warnings
- breaking As a pre-1.0 package (currently 0.2.x), minor version updates of `nuxt-graphql-client` may introduce breaking changes without explicit mention in the release notes. Review changelogs carefully during upgrades.
- gotcha Using `localStorage` for token storage does not support Server-Side Rendering (SSR). This can lead to authentication issues or hydration mismatches during the initial server render.
- gotcha When implementing custom authentication logic via the `gql:auth:init` hook in a Nuxt plugin, direct calls to Nuxt composables like `useState` or `useCookie` inside the hook will result in a 'Nuxt instance unavailable' error on the server-side, due to context loss after the first awaited call.
- gotcha When configuring multiple GraphQL clients, schema merging issues can occur if different endpoints define types with the same name but conflicting field definitions (e.g., two `PageInfo` types with `endCursor` having different underlying types). This prevents schema loading during code generation.
Install
-
npm install nuxt-graphql-client -
yarn add nuxt-graphql-client -
pnpm add nuxt-graphql-client
Imports
- useGql
import { useGql } from '#graphql-client/composables'; - useAsyncGql
import { useGql } from '#graphql-client/composables';import { useAsyncGql } from '#graphql-client/composables'; - Gql<OperationName>
import { GetUsers } from '#graphql-client/generated';const { data } = await GqlGetUsers(); - useGqlToken
import { useGqlToken } from '#graphql-client/composables'; - GqlError
import { GqlError } from '#graphql-client/types';
Quickstart
// 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>