Events

Nuxt provides a powerful event system powered by hookable.

Events

Using events is a great way to decouple your application and allow for more flexible and modular communication between different parts of your code. Events can have multiple listeners that do not depend on each other. For example, you may wish to send an email to your user each time an order has shipped. Instead of coupling your order processing code to your email code, you can emit an event which a listener can receive and use to dispatch an email.

The Nuxt event system is powered by unjs/hookable, which is the same library that powers the Nuxt hooks system.

Creating Events and Listeners

You can create your own custom events using the hook method:

const nuxtApp = useNuxtApp()

nuxtApp.hook('app:user:registered', payload => {
  console.log('A new user has registered!', payload)
})

To emit an event and notify any listeners, use callHook:

const nuxtApp = useNuxtApp()

await nuxtApp.callHook('app:user:registered', {
  id: 1,
  name: 'John Doe',
})

You can also use the payload object to enable two-way communication between the emitter and listeners. Since the payload is passed by reference, a listener can modify it to send data back to the emitter.

const nuxtApp = useNuxtApp()

nuxtApp.hook('app:user:registered', payload => {
  payload.message = 'Welcome to our app!'
})

const payload = {
  id: 1,
  name: 'John Doe',
}

await nuxtApp.callHook('app:user:registered', {
  id: 1,
  name: 'John Doe',
})

// payload.message will be 'Welcome to our app!'
You can inspect all events using the Nuxt DevTools Hooks panel.

Augmenting Types

You can augment the types of hooks provided by Nuxt.

import { HookResult } from "@nuxt/schema";

declare module '#app' {
  interface RuntimeNuxtHooks {
    'your-nuxt-runtime-hook': () => HookResult
  }
  interface NuxtHooks {
    'your-nuxt-hook': () => HookResult
  }
}

declare module 'nitropack' {
  interface NitroRuntimeHooks {
    'your-nitro-hook': () => void;
  }
}