nuxt-graphql-client
repository·main·Indexed 19 days ago
https://github.com/diizzayy/nuxt-graphql-clientA minimal GraphQL client and code generation tool optimized for Nuxt 3. It provides full TypeScript support, Hot Module Reload (HMR) for GraphQL documents, and leverages graphql-request and graphql-code-generator. Key features include zero configuration, automatically generated Gql functions, and composables such as useAsyncGql, useGql, and useGqlToken for managing requests, authorization, and error handling.
What's inside nuxt-graphql-client
- nuxt-graphql-client is a minimal GraphQL client designed for Nuxt 3 that includes built-in code generation. It provides a seamless developer experience with full TypeScript support and Hot Module Reload (HMR) for GraphQL documents, meaning changes to your queries are reflected immediately without manual regeneration steps.
Authenticate Codegen Introspection
mainIf your GraphQL API requires authentication to run introspection queries (used for generating types), you must provide a token to the client.
Recommended approach: Add the token to your
.envfile using theGQL_<CLIENT_NAME>_TOKENformat. This token will only live server-side and will not be passed to the browser.How to associate GraphQL operations with specific clients
mainWhen using Multiple Client Mode, you must tell the module which client an operation belongs to. You can do this using one of three methods, listed in order of precedence:
- File Suffix (Highest Precedence): Name your GraphQL file with the client name as a suffix before the extension:
<clientname>.gqlor<clientname>.graphql. For example,example.github.gqlwill be linked to thegithubclient. - Directory Name: Place your GraphQL files inside a folder named after the client. For example, files in
./queries/spacex/will be linked to thespacexclient. - Default Fallback (Lowest Precedence): If neither of the above methods is used, the operation is automatically linked to the
defaultclient.
- File Suffix (Highest Precedence): Name your GraphQL file with the client name as a suffix before the extension:
How to chain multiple GraphQL operations in Nuxt
mainDue to how Nuxt 3 handles SSR, the Nuxt instance context is lost after the first
awaitstatement. This means you cannot call multiple Gql Functions sequentially if they rely on the Nuxt context (likeuseStateoruseRoute) inside an async function.The Problem (Invalid Approach)
Calling a second Gql Function after an
awaitwill fail because the context is gone.export const useExample = async () => { const { user } = await GqlUser() // Context lost here const { relations } = await GqlRelations({ id: user.id }) // Fails }The Solution (Recommended Approach)
Use the
useGqlcomposable to create a single instance. This allows you to perform multiple queries/mutations while maintaining the necessary context. Additionally, ensure any Nuxt composables (likeuseState) are called before the firstawaitstatement.export const useExample = async () => { const GqlInstance = useGql() // Access Nuxt composables BEFORE the first await const myState = useState('example') const { user } = await GqlInstance('user') const { relations } = await GqlInstance('relations', { id: user.id }) // myState is still accessible }export const useExample = async () => { const GqlInstance = useGql() const myState = useState('example') const { user } = await GqlInstance('user') const { relations } = await GqlInstance('relations', { id: user.id }) }Key features of nuxt-graphql-client
mainThe module provides the following core capabilities:
- Zero Configuration: Works out of the box with minimal setup.
- Nuxt 3 Support: Built specifically for the Nuxt 3 ecosystem.
- Full TypeScript Support: Provides type safety for your GraphQL queries.
- HMR for GraphQL documents: Automatically updates types and client state when GraphQL documents change.
- Minimalist Core: Leverages
graphql-requestfor the client andgraphql-code-generatorfor code generation.
Identify the default GraphQL client
mainThe
defaultclient is the fallback for any GraphQL operation that does not explicitly specify a client via file naming or directory structure.In Multiple Client Mode, the default client is determined by:
- The first client configured in the
clientsobject. - Or, explicitly setting a client name to
defaultin the Nuxt Configuration.
- The first client configured in the
Generate types from a local schema file
mainIf your GraphQL API is not publicly available or you prefer not to use introspection over the network, you can provide a path to a local schema file. The module will use this file to generate types for your GraphQL operations. Provide the path relative to your project root in the
schemaproperty within your client configuration.export default defineNuxtConfig({ modules: ['nuxt-graphql-client'], runtimeConfig: { public: { 'graphql-client': { clients: { default: { schema: '<relative_path_to_schema_file>', } } } } } })Write and generate GraphQL operations
mainOperations (queries and mutations) must be written in
.gqlor.graphqlfiles. Writing operations directly within SFC components is not supported.nuxt-graphql-clientautomatically parses these files and generates corresponding functions and types. The generated function name is derived from the GraphQL operation name.Example Operation: Create a file at
./queries/starlink.gql:query launches($limit: Int = 5) { launches(limit: $limit) { id launch_year mission_name } }This will generate a function named
GqlLaunches()(based on the operation namelaunches) that is fully typed based on the GraphQL document. To trigger code generation, run your development server (e.g.,yarn dev).Configure multiple GraphQL clients
mainTo interact with multiple GraphQL APIs, add a
clientskey to thegraphql-clientproperty within your NuxtruntimeConfig.public. Each key in theclientsobject represents a unique client name.If you configure more than one client, the module enters Multiple Client Mode. In this mode, you must explicitly associate GraphQL operations with a specific client using file naming or directory structures, otherwise, they will fall back to the
defaultclient.import { defineNuxtConfig } from 'nuxt' export default defineNuxtConfig({ modules: ['nuxt-graphql-client'], runtimeConfig: { public: { 'graphql-client': { clients: { default: 'https://spacex-production.up.railway.app/', github: { host: 'https://api.github.com/graphql', token: 'your_access_token', }, countries: { host: 'https://countries.trevorblades.com/graphql', token: { name: 'X-Custom-Auth', value: 'your_access_token' } } } } } } })Install Nuxt GraphQL Client
mainTo add the
nuxt-graphql-clientmodule to your Nuxt project, use the Nuxt CLI command. This module provides a minimal GraphQL client combined with automatic TypeScript code generation.npx nuxi@latest module add graphql-clientInstall and setup nuxt-graphql-client
mainTo use
nuxt-graphql-clientin a Nuxt 3 application, follow these steps:Install the module using the Nuxt CLI:
npx nuxi@latest module add graphql-clientEnable the module in your
nuxt.config.ts:import { defineNuxtConfig } from 'nuxt/config' export default defineNuxtConfig({ modules: ['nuxt-graphql-client'], })Configure the GraphQL API URL by providing a
GQL_HOST. You can define this innuxt.config.tsor via a.envfile. Note that aGQL_HOSTvalue in.envwill overwrite the value defined inruntimeConfig.
Using nuxt.config.ts:
export default defineNuxtConfig({ modules: ['nuxt-graphql-client'], runtimeConfig: { public: { GQL_HOST: 'https://your-api-url.com/' } } })Using .env:
GQL_HOST="https://your-api-url.com/"npx nuxi@latest module add graphql-clientUse automatically generated Gql Functions
mainGql Functions are automatically generated and imported based on the GraphQL operations defined in your project. They allow you to execute queries and mutations as simple asynchronous functions.
Naming Convention
Functions are named using the pattern
Gql+[OperationName]. For example, a query namedGetUsersbecomes the functionGqlGetUsers().Requirements
- Operation Names: Every GraphQL operation must have a name. Anonymous operations (e.g.,
query { ... }) are skipped and will not generate a Gql Function. - File Location: Operations must be written in
.gqlor.graphqlfiles located anywhere in your project. - No SFC Writing: Writing GraphQL operations directly inside Single File Components (SFCs) is not supported.
query GetUsers { users { id name } } mutation LoginUser($email: String!, $password: String!) { login(email: $email, password: $password) { id name } }// Generated functions are automatically imported async function loadUsers() { const result = await GqlGetUsers() } async function handleLogin(email: string, password: string) { const result = await GqlLoginUser(email, password) }- Operation Names: Every GraphQL operation must have a name. Anonymous operations (e.g.,