defineNuxtPlugin is a helper function for creating Nuxt plugins with enhanced functionality and type safety. This utility normalizes different plugin formats into a consistent structure that works seamlessly within Nuxt's plugin system.
export default defineNuxtPlugin((nuxtApp) => {
  // Doing something with nuxtApp
})
export function defineNuxtPlugin<T extends Record<string, unknown>> (plugin: Plugin<T> | ObjectPlugin<T>): Plugin<T> & ObjectPlugin<T>
type Plugin<T> = (nuxt: NuxtApp) => Promise<void> | Promise<{ provide?: T }> | void | { provide?: T }
interface ObjectPlugin<T> {
  name?: string
  enforce?: 'pre' | 'default' | 'post'
  dependsOn?: string[]
  order?: number
  parallel?: boolean
  setup?: Plugin<T>
  hooks?: Partial<RuntimeNuxtHooks>
  env?: {
    islands?: boolean
  }
}
plugin: A plugin can be defined in two ways:
NuxtApp instance and can return a promise with an potential object with a provide property if you want to provide a helper on NuxtApp instance.name, enforce, dependsOn, order, parallel, setup, hooks, and env.| Property | Type | Required | Description | 
|---|---|---|---|
| name | string | false | Optional name for the plugin, useful for debugging and dependency management. | 
| enforce | 'pre'|'default'|'post' | false | Controls when the plugin runs relative to other plugins. | 
| dependsOn | string[] | false | Array of plugin names this plugin depends on. Ensures proper execution order. | 
| order | number | false | This allows more granular control over plugin order and should only be used by advanced users. It overrides the value of enforceand is used to sort plugins. | 
| parallel | boolean | false | Whether to execute the plugin in parallel with other parallel plugins. | 
| setup | Plugin<T> | false | The main plugin function, equivalent to a function plugin. | 
| hooks | Partial<RuntimeNuxtHooks> | false | Nuxt app runtime hooks to register directly. | 
| env | { islands?: boolean } | false | Set this value to falseif you don't want the plugin to run when rendering server-only or island components. | 
The example below demonstrates a simple plugin that adds global functionality:
export default defineNuxtPlugin((nuxtApp) => {
  // Add a global method
  return {
    provide: {
      hello: (name: string) => `Hello ${name}!`,
    },
  }
})
The example below shows the object syntax with advanced configuration:
export default defineNuxtPlugin({
  name: 'my-plugin',
  enforce: 'pre',
  async setup (nuxtApp) {
    // Plugin setup logic
    const data = await $fetch('/api/config')
    return {
      provide: {
        config: data,
      },
    }
  },
  hooks: {
    'app:created' () {
      console.log('App created!')
    },
  },
})