Plugins directory

Nuxt will automatically read the files in your plugins directory and load them. You can use .server or .client suffix in the file name to load a plugin only on the server or client side.

All plugins in your plugins/ directory are auto-registered, so you should not add them to your nuxt.config separately.

Which files are registered

Only files at the top level of the plugins/ directory (or index files within any subdirectories) will be registered as plugins.

For example:

  1. plugins
  2. | - myPlugin.ts
  3. | - myOtherPlugin
  4. | --- supportingFile.ts
  5. | --- componentToRegister.vue
  6. | --- index.ts

Only myPlugin.ts and myOtherPlugin/index.ts would be registered.

Creating plugins

The only argument passed to a plugin is nuxtApp.

  1. export default defineNuxtPlugin(nuxtApp => {
  2. // Doing something with nuxtApp
  3. })

Automatically providing helpers

If you would like to provide a helper on the NuxtApp instance, return it from the plugin under a provide key. For example:

  1. export default defineNuxtPlugin(() => {
  2. return {
  3. provide: {
  4. hello: () => 'world'
  5. }
  6. }
  7. })

In another file you can use this:

  1. <template>
  2. <div>
  3. {{ $hello() }}
  4. </div>
  5. </template>
  6. <script setup lang="ts">
  7. // alternatively, you can also use it here
  8. const { $hello } = useNuxtApp()
  9. </script>

Typing plugins

If you return your helpers from the plugin, they will be typed automatically; you’ll find them typed for the return of useNuxtApp() and within your templates.

If you need to use a provided helper within another plugin, you can call useNuxtApp() to get the typed version. But in general, this should be avoided unless you are certain of the plugins’ order.

Advanced

For advanced use-cases, you can declare the type of injected properties like this:

index.d.ts

  1. declare module '#app' {
  2. interface NuxtApp {
  3. $hello (msg: string): string
  4. }
  5. }
  6. declare module '@vue/runtime-core' {
  7. interface ComponentCustomProperties {
  8. $hello (msg: string): string
  9. }
  10. }
  11. export { }

Vue plugins

If you want to use Vue plugins, like vue-gtag to add Google Analytics tags, you can use a Nuxt plugin to do so.

There is an Open RFC to make this even easier! See nuxt/framework#1175

First, install the plugin you want.

  1. yarn add --dev vue-gtag-next

Then create a plugin file plugins/vue-gtag.client.js.

  1. import VueGtag from 'vue-gtag-next'
  2. export default defineNuxtPlugin((nuxtApp) => {
  3. nuxtApp.vueApp.use(VueGtag, {
  4. property: {
  5. id: 'GA_MEASUREMENT_ID'
  6. }
  7. })
  8. })

🔎

Read and edit a live example in Examples > App > Plugins