Advanced

Custom client

NuxtOpenFetch uses Nuxt/Nitro plugins to provide fetch clients to the app/server

If you need to add non-serializable fetch options which can't be specified in the Nuxt config, such as onRequest, onResponse etc, you can create custom Nuxt plugin (and Nitro plugin if you use client inside the server handler).

First you need to disable the default plugin:

nuxt.config.ts
export default 
defineNuxtConfig
({
openFetch
: {
disableNuxtPlugin
: true,
// ... }, })

For example if you need to add logging on each request:

plugins/openFetch.ts
export default defineNuxtPlugin({
  enforce: 'pre', // clients will be ready to use by other plugins, Pinia stores etc.
  setup() {
    const clients = useRuntimeConfig().public.openFetch
    const localFetch = useRequestFetch()

    return {
      provide: Object.entries(clients).reduce((acc, [name, options]) => ({
        ...acc,
        [name]: createOpenFetch(options, localFetch)

        // or add the logging:

        // [name]: createOpenFetch(localOptions => ({
        //   ...options,
        //   ...localOptions,
        //   onRequest(ctx) {
        //     console.log('My logging', ctx.request)
        //     return localOptions?.onRequest?.(ctx)
        //   }
        // }), localFetch)
      }), {})
    }
  }
})

Same way you can disable the Nitro plugin and provide your own fetch client:

nuxt.config.ts
export default 
defineNuxtConfig
({
openFetch
: {
disableNitroPlugin
: true,
// ... }, })
server/plugins/openFetch.ts
import type { NitroApp } from 'nitropack'
import { createOpenFetch, useRuntimeConfig } from '#imports'

type NitroAppPlugin = (nitro: NitroApp) => void

// Workaround to add another property to NitroApp
function defineNitroPlugin(def: NitroAppPlugin): NitroAppPlugin {
  return def
}

export default defineNitroPlugin((nitroApp) => {
  const clients = useRuntimeConfig().public.openFetch

  Object.entries(clients).forEach(([name, options]) => {
    nitroApp[`$${name}`] = createOpenFetch(options, nitroApp.localFetch)
  })
})

Copyright © 2024