Skip to content

Composable configuration

If you use the provided useGraphqlQuery/useGraphqlMutation composables, you can use the useGraphqlState composable to set custom fetch options.

Nuxt's $fetch uses ofetch behind the scenes, so check out their documentation for all available options.

Configuration is usually done by creating a Nuxt plugin in your app that loads and sets the configuration. This can technically also be done anywhere in your app (e.g. in page components), but it is advised to only do this in a single place (the plugin).

Example: Pass static custom headers

In this example a static header value is set which will be sent for every request initiated by this module's useGraphqlQuery or useGraphqlMutation composables to the server route.

WARNING

The state is only used for requests made from within a Nuxt app context (e.g. pages, route middleware, etc.). Usually this is used to "pass" information from the client/browser context to the middleware.

typescript
// plugins/graphqlConfig.ts

export default defineNuxtPlugin((NuxtApp) => {
  // Get the configuration state.
  const state = useGraphqlState()

  if (!state) {
    return
  }

  state.fetchOptions = {
    headers: {
      CustomHeader: 'foobar',
    },
  }
}

Example: Alter the request using interceptors

By using ofetch's onRequest interceptor you can alter the request right before it is made.

In this example a query parameter is added to every request. Useful if you use an HTTP cache and want to make sure that after deploying a new release (that changes the build hash), all requests to the server route won't be served from cache.

typescript
// plugins/graphqlConfig.ts

export default defineNuxtPlugin((NuxtApp) => {
  const state = useGraphqlState()

  if (!state) {
    return
  }

  // A hash generated at build time and passed in publicRuntimeConfig.
  const { buildHash } = useRuntimeConfig()

  state.fetchOptions = {
    async onRequest({ request, options }) {
      if (!options.params) {
        options.params = {}
      }
      options.params.hash = buildHash
    },
  }
}

Released under the MIT License.