NuxtN
Nuxt8mo ago
9 replies
Dawit

Passing module options to runtime

When working on a Nuxt 3 module, what is the best way to expose the module's options (possibly defined in
nuxt.config.ts
) to parts of the runtime code such as components and server handlers?
Solution
----------------------
To expose module options to runtime in a type-safe way in Nuxt 3, you should:

1. Define a Type for Your Module Options:
Create a TypeScript interface for your module options.

2. Use That Type in Your Module:
Pass your type to defineNuxtModule<YourOptionsType>() so that options are type-checked in the module setup.

3. Augment the RuntimeConfig Type:
Extend the PublicRuntimeConfig (or RuntimeConfig for server-only) interface in a index.d.ts file to include your module's options. This ensures that when you access useRuntimeConfig().public.myModule, TypeScript knows the shape of your options.

Example:

// types/my-module.d.ts
export interface MyModuleOptions {
  foo: string
  bar?: number
}


// nuxt.config.ts
import type { MyModuleOptions } from './types/my-module'

export default defineNuxtConfig({
  modules: [
    // your module
  ],
  myModule: {
    foo: 'hello',
    bar: 42
  } as MyModuleOptions,
  runtimeConfig: {
    public: {
      myModule: {} as MyModuleOptions
    }
  }
})


// my-module.ts
import { defineNuxtModule } from '@nuxt/kit'
import type { MyModuleOptions } from './types/my-module'
import { defu } from 'defu'

export default defineNuxtModule<MyModuleOptions>({
  meta: { name: 'my-module' },
  defaults: {
    foo: 'default'
  },
  setup(options, nuxt) {
    nuxt.options.runtimeConfig.public.myModule = defu(
      nuxt.options.runtimeConfig.public.myModule,
      options
    )
  }
})


// index.d.ts (in your project root)
import type { MyModuleOptions } from './types/my-module'

declare module 'nuxt/schema' {
  interface PublicRuntimeConfig {
    myModule: MyModuleOptions
  }
}
export {}


Now, when you use:

const options = useRuntimeConfig().public.myModule
Was this page helpful?