Composables

Composables are auto imported functions that provide additional functionalities.

useGql

const GqlInstance = useGql()

const data = await GqlInstance('<operation_name>', <variables>)

useAsyncGql

Asynchronously query data that is required to load a page or component. This method takes an operation parameter which is the Operation name of the GraphQL query to be executed.

A unique key is automatically generated based on the operation name, it's pertinent client name and the query parameters.

const { data } = await useAsyncGql('launches', { limit: 5 });

const { data } = await useAsyncGql({
  operation: 'launches',
  variables: { limit: 5 }
});

// The examples above are equivalent to:
const { data } = await useAsyncData('<data-key>', () => GqlLaunches({ limit: 5 }))

useGqlCors

Add CORS headers to subsequent requests

useGqlCors({ credentials: 'same-origin' })

useGqlToken

Add Authorization header to subsequent requests.

Bearer token

useGqlToken('secret_token')

// Add `Bearer` token to a specific client
useGqlToken('my_github_token', { client: 'github' })

Custom token

useGqlToken({
  token: 'secret_token',
  config: {
    type: 'Bearer',
    name: 'X-Custom-Auth'
  }
})

Clear token

// Clear token from default client
useGqlToken(null)

// Clear token from a specific client
useGqlToken({ token: null, client: '<client>' })

useGqlHeaders

Add the specified headers to subsequent requests.

useGqlHeaders({ 'X-Custom-Header': 'value' })

// Add headers to a specific client.
useGqlHeaders({ 'X-CSRF-TOKEN': 'value' }, 'client-name')

Reset headers

useGqlHeaders(null)

// Reset headers for a specific client.
useGqlHeaders({ headers: null, client: '<client>' })

useGqlError

Capture GraphQL errors at the earliest point.

As a proactive measure, the callback provided to useGqlError is only executed on client-side. This is to prevent unwarranted side-effects as well as to allow nuxt context reliant calls such as useState, useRoute, useCookie and other internal Nuxt 3 composables to be made, as this isn't currently possible on server-side due to a vue 3 limitation where context is lost after the first awaited call.

Only a single error handler can be defined.
plugins/onError.ts
export default defineNuxtPlugin(() => {
  useGqlError((err) => {
    // Only log during development
    if (process.env.NODE_ENV !== 'production') {
      for (const gqlError of err.gqlErrors) {
        console.error('[nuxt-graphql-client] [GraphQL error]', {
          client: err.client,
          statusCode: err.statusCode,
          operationType: err.operationType,
          operationName: err.operationName,
          gqlError
        })
      }
    }

    // Handle different error cases
    const tokenExpired = err.gqlErrors.some(e => e.message.includes('id-token-expired'))
    const tokenRevoked = err.gqlErrors.some(e => e.message.includes('id-token-revoked'))
    const unauthorized = err.gqlErrors.some(e => e.message.includes('invalid-claims') || e.message.includes('insufficient-permission'))

    // take action accordingly...
  })
})

useGqlHost

Change the host of a GraphQL Client at runtime.

export default defineNuxtPlugin(() => {
  // Change the host of the default client
  useGqlHost('<host>')

  // Change the host of a specific client
  useGqlHost('<host>', '<client>')

  // Add query parameters to the preconfigured host
  useGqlHost('?param1=one&param2=two')
})