Nuxt's configuration and hooks systems make it possible to customize every aspect of Nuxt and add any integration you might need (Vue plugins, CMS, server routes, components, logging, etc.).
Nuxt Modules are functions that sequentially run when starting Nuxt in development mode using nuxt dev or building a project for production with nuxt build.
With modules, you can encapsulate, properly test, and share custom solutions as npm packages without adding unnecessary boilerplate to your project, or requiring changes to Nuxt itself.
We recommend you get started with Nuxt Modules using our starter template:
npm create nuxt -- -t module my-module
yarn create nuxt -t module my-module
pnpm create nuxt -t module my-module
bun create nuxt -- -t module my-module
This will create a my-module project with all the boilerplate necessary to develop and publish your module.
Next steps:
my-module in your IDE of choicenpm run dev:prepareLearn how to perform basic tasks with the module starter.
While your module source code lives inside the src directory, in most cases, to develop a module, you need a Nuxt application. That's what the playground directory is about. It's a Nuxt application you can tinker with that is already configured to run with your module.
You can interact with the playground like with any Nuxt application.
npm run dev, it should reload itself as you make changes to your module in the src directorynpm run dev:buildnuxt commands can be used against the playground directory (e.g. nuxt <COMMAND> playground). Feel free to declare additional dev:* scripts within your package.json referencing them for convenience.The module starter comes with a basic test suite:
npm run lintnpm run test or npm run test:watchNuxt Modules come with their own builder provided by @nuxt/module-builder. This builder doesn't require any configuration on your end, supports TypeScript, and makes sure your assets are properly bundled to be distributed to other Nuxt applications.
You can build your module by running npm run prepack.
playground takes care of it while developing, and the release script also has you covered when publishing.npm login.While you can publish your module by bumping its version and using the npm publish command, the module starter comes with a release script that helps you make sure you publish a working version of your module to npm and more.
To use the release script, first, commit all your changes (we recommend you follow Conventional Commits to also take advantage of automatic version bump and changelog update), then run the release script with npm run release.
When running the release script, the following will happen:
npm run lint)npm run test)npm run prepack)release script in your package.json to better suit your needs.Nuxt Modules come with a variety of powerful APIs and patterns allowing them to alter a Nuxt application in pretty much any way possible. This section teaches you how to take advantage of those.
We can consider two kinds of Nuxt Modules:
modules directory.In either case, their anatomy is similar.
src/module.ts.The module definition is the entry point of your module. It's what gets loaded by Nuxt when your module is referenced within a Nuxt configuration.
At a low level, a Nuxt Module definition is a simple, potentially asynchronous, function accepting inline user options and a nuxt object to interact with Nuxt.
export default function (inlineOptions, nuxt) {
// You can do whatever you like here..
console.log(inlineOptions.token) // `123`
console.log(nuxt.options.dev) // `true` or `false`
nuxt.hook('ready', (nuxt) => {
console.log('Nuxt is ready')
})
}
You can get type-hint support for this function using the higher-level defineNuxtModule helper provided by Nuxt Kit.
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule((options, nuxt) => {
nuxt.hook('pages:extend', (pages) => {
console.log(`Discovered ${pages.length} pages`)
})
})
However, we do not recommend using this low-level function definition. Instead, to define a module, we recommend using the object-syntax with meta property to identify your module, especially when publishing to npm.
This helper makes writing Nuxt modules more straightforward by implementing many common patterns needed by modules, guaranteeing future compatibility and improving the experience for both module authors and users.
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
// Usually the npm package name of your module
name: '@nuxtjs/example',
// The key in `nuxt.config` that holds your module options
configKey: 'sample',
// Compatibility constraints
compatibility: {
// Semver version of supported nuxt versions
nuxt: '>=3.0.0',
},
},
// Default configuration options for your module, can also be a function returning those
defaults: {},
// Shorthand sugar to register Nuxt hooks
hooks: {},
// Configuration for other modules - this does not ensure the module runs before
// your module, but it allows you to change the other module's configuration before it runs
moduleDependencies: {
'some-module': {
// You can specify a version constraint for the module. If the user has a different
// version installed, Nuxt will throw an error on startup.
version: '>=2',
// By default moduleDependencies will be added to the list of modules to be installed
// by Nuxt unless `optional` is set.
optional: true,
// Any configuration that should override `nuxt.options`.
overrides: {},
// Any configuration that should be set. It will override module defaults but
// will not override any configuration set in `nuxt.options`.
defaults: {},
},
},
// The function holding your module logic, it can be asynchronous
setup (moduleOptions, nuxt) {
// ...
},
})
Ultimately defineNuxtModule returns a wrapper function with the lower level (inlineOptions, nuxt) module signature. This wrapper function applies defaults and other necessary steps before calling your setup function:
defaults and meta.configKey for automatically merging module optionsmeta.name or meta.configKeygetOptions and getMeta for internal usage of NuxtdefineNuxtModule from the latest version of @nuxt/kitsrc/runtime.Modules, like everything in a Nuxt configuration, aren't included in your application runtime. However, you might want your module to provide, or inject runtime code to the application it's installed on. That's what the runtime directory enables you to do.
Inside the runtime directory, you can provide any kind of assets related to the Nuxt App:
To the server engine, Nitro:
Or any other kind of asset you want to inject in users' Nuxt applications:
You'll then be able to inject all those assets inside the application from your module definition.
#imports or alike.
node_modules (the location where a published module will eventually live) for performance reasons.Modules come with a set of first-party tools to help you with their development.
@nuxt/module-builderNuxt Module Builder is a zero-configuration build tool taking care of all the heavy lifting to build and ship your module. It ensures proper compatibility of your module build artifact with Nuxt applications.
@nuxt/kitNuxt Kit provides composable utilities to help your module interact with Nuxt applications. It's recommended to use Nuxt Kit utilities over manual alternatives whenever possible to ensure better compatibility and code readability of your module.
@nuxt/test-utilsNuxt Test Utils is a collection of utilities to help set up and run Nuxt applications within your module tests.
Find here common patterns used to author modules.
Nuxt configuration can be read and altered by modules. Here's an example of a module enabling an experimental feature.
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
// We create the `experimental` object if it doesn't exist yet
nuxt.options.experimental ||= {}
nuxt.options.experimental.componentIslands = true
},
})
When you need to handle more complex configuration alterations, you should consider using defu.
Because modules aren't part of the application runtime, their options aren't either. However, in many cases, you might need access to some of these module options within your runtime code. We recommend exposing the needed config using Nuxt's runtimeConfig.
import { defineNuxtModule } from '@nuxt/kit'
import { defu } from 'defu'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.options.runtimeConfig.public.myModule = defu(nuxt.options.runtimeConfig.public.myModule, {
foo: options.foo,
})
},
})
Note that we use defu to extend the public runtime configuration the user provides instead of overwriting it.
You can then access your module options in a plugin, component, the application like any other runtime configuration:
import { useRuntimeConfig } from '@nuxt/kit'
const options = useRuntimeConfig().public.myModule
addPluginPlugins are a common way for a module to add runtime logic. You can use the addPlugin utility to register them from your module.
import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
// Create resolver to resolve relative paths
const resolver = createResolver(import.meta.url)
addPlugin(resolver.resolve('./runtime/plugin'))
},
})
addComponentIf your module should provide Vue components, you can use the addComponent utility to add them as auto-imports for Nuxt to resolve.
import { addComponent, createResolver, defineNuxtModule, useRuntimeConfig } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
// From the runtime directory
addComponent({
name: 'MySuperComponent', // name of the component to be used in vue templates
export: 'MySuperComponent', // (optional) if the component is a named (rather than default) export
filePath: resolver.resolve('runtime/components/MySuperComponent.vue'),
})
// From a library
addComponent({
name: 'MyAwesomeComponent', // name of the component to be used in vue templates
export: 'MyAwesomeComponent', // (optional) if the component is a named (rather than default) export
filePath: '@vue/awesome-components',
})
},
})
Alternatively, you can add an entire directory by using addComponentsDir.
import { addComponentsDir, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
addComponentsDir({
path: resolver.resolve('runtime/components'),
})
},
})
addImports and addImportsDirIf your module should provide composables, you can use the addImports utility to add them as auto-imports for Nuxt to resolve.
import { addImports, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
addImports({
name: 'useComposable', // name of the composable to be used
as: 'useComposable',
from: resolver.resolve('runtime/composables/useComposable'), // path of composable
})
},
})
Alternatively, you can add an entire directory by using addImportsDir.
import { addImportsDir, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
addImportsDir(resolver.resolve('runtime/composables'))
},
})
addServerHandlerimport { addServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
addServerHandler({
route: '/api/hello',
handler: resolver.resolve('./runtime/server/api/hello/index.get'),
})
},
})
You can also add a dynamic server route:
import { addServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
addServerHandler({
route: '/api/hello/:name',
handler: resolver.resolve('./runtime/server/api/hello/[name].get'),
})
},
})
If your module should provide other kinds of assets, they can also be injected. Here's a simple example module injecting a stylesheet through Nuxt's css array.
import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
nuxt.options.css.push(resolver.resolve('./runtime/style.css'))
},
})
And a more advanced one, exposing a folder of assets through Nitro's publicAssets option:
import { createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
const resolver = createResolver(import.meta.url)
nuxt.hook('nitro:config', (nitroConfig) => {
nitroConfig.publicAssets ||= []
nitroConfig.publicAssets.push({
dir: resolver.resolve('./runtime/public'),
maxAge: 60 * 60 * 24 * 365, // 1 year
})
})
},
})
If your module depends on other modules, you can specify them using the moduleDependencies option. This provides a more robust way to handle module dependencies with version constraints and configuration merging:
import { createResolver, defineNuxtModule } from '@nuxt/kit'
const resolver = createResolver(import.meta.url)
export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'my-module',
},
moduleDependencies: {
'@nuxtjs/tailwindcss': {
// You can specify a version constraint for the module
version: '>=6',
// Any configuration that should override `nuxt.options`
overrides: {
exposeConfig: true,
},
// Any configuration that should be set. It will override module defaults but
// will not override any configuration set in `nuxt.options`
defaults: {
config: {
darkMode: 'class',
content: {
files: [
resolver.resolve('./runtime/components/**/*.{vue,mjs,ts}'),
resolver.resolve('./runtime/*.{mjs,js,ts}'),
],
},
},
},
},
},
setup (options, nuxt) {
// We can inject our CSS file which includes Tailwind's directives
nuxt.options.css.push(resolver.resolve('./runtime/assets/styles.css'))
},
})
moduleDependencies option replaces the deprecated installModule function and ensures proper setup order and configuration merging.Lifecycle hooks allow you to expand almost every aspect of Nuxt. Modules can hook to them programmatically or through the hooks map in their definition.
import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
// Hook to the `app:error` hook through the `hooks` map
hooks: {
'app:error': (err) => {
console.info(`This error happened: ${err}`)
},
},
setup (options, nuxt) {
// Programmatically hook to the `pages:extend` hook
nuxt.hook('pages:extend', (pages) => {
console.info(`Discovered ${pages.length} pages`)
})
},
})
close hook is available for this.import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.hook('close', async (nuxt) => {
// Your custom code here
})
},
})
Modules can also define and call their own hooks, which is a powerful pattern for making your module extensible.
If you expect other modules to be able to subscribe to your module's hooks, you should call them in the modules:done hook. This ensures that all other modules have had a chance to be set up and register their listeners to your hook during their own setup function.
// my-module/module.ts
import { defineNuxtModule } from '@nuxt/kit'
export interface ModuleHooks {
'my-module:custom-hook': (payload: { foo: string }) => void
}
export default defineNuxtModule({
setup (options, nuxt) {
// Call your hook in `modules:done`
nuxt.hook('modules:done', async () => {
const payload = { foo: 'bar' }
await nuxt.callHook('my-module:custom-hook', payload)
})
},
})
If you need to add a virtual file that can be imported into the user's app, you can use the addTemplate utility.
import { addTemplate, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
// The file is added to Nuxt's internal virtual file system and can be imported from '#build/my-module-feature.mjs'
addTemplate({
filename: 'my-module-feature.mjs',
getContents: () => 'export const myModuleFeature = () => "hello world !"',
})
},
})
For the server, you should use the addServerTemplate utility instead.
import { addServerTemplate, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
// The file is added to Nitro's virtual file system and can be imported in the server code from 'my-server-module.mjs'
addServerTemplate({
filename: 'my-server-module.mjs',
getContents: () => 'export const myServerModule = () => "hello world !"',
})
},
})
You might also want to add a type declaration to the user's project (for example, to augment a Nuxt interface
or provide a global type of your own). For this, Nuxt provides the addTypeTemplate utility that both
writes a template to the disk and adds a reference to it in the generated nuxt.d.ts file.
If your module should augment types handled by Nuxt, you can use addTypeTemplate to perform this operation:
import { addTemplate, addTypeTemplate, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
addTypeTemplate({
filename: 'types/my-module.d.ts',
getContents: () => `// Generated by my-module
interface MyModuleNitroRules {
myModule?: { foo: 'bar' }
}
declare module 'nitropack' {
interface NitroRouteRules extends MyModuleNitroRules {}
interface NitroRouteConfig extends MyModuleNitroRules {}
}
export {}`,
})
},
})
If you need more granular control, you can use the prepare:types hook to register a callback that will inject your types.
const template = addTemplate({ /* template options */ })
nuxt.hook('prepare:types', ({ references }) => {
references.push({ path: template.dst })
})
If you need to update your templates/virtual files, you can leverage the updateTemplates utility like this :
nuxt.hook('builder:watch', (event, path) => {
if (path.includes('my-module-feature.config')) {
// This will reload the template that you registered
updateTemplates({ filter: t => t.filename === 'my-module-feature.mjs' })
}
})
Testing helps ensuring your module works as expected given various setup. Find in this section how to perform various kinds of tests against your module.
Nuxt Test Utils is the go-to library to help you test your module in an end-to-end way. Here's the workflow to adopt with it:
test/fixtures/*@nuxt/test-utils (e.g. fetching a page)In practice, the fixture:
// 1. Create a Nuxt application to be used as a "fixture"
import MyModule from '../../../src/module'
export default defineNuxtConfig({
ssr: true,
modules: [
MyModule,
],
})
And its test:
import { describe, expect, it } from 'vitest'
import { fileURLToPath } from 'node:url'
import { $fetch, setup } from '@nuxt/test-utils/e2e'
describe('ssr', async () => {
// 2. Setup Nuxt with this fixture inside your test file
await setup({
rootDir: fileURLToPath(new URL('./fixtures/ssr', import.meta.url)),
})
it('renders the index page', async () => {
// 3. Interact with the fixture using utilities from `@nuxt/test-utils`
const html = await $fetch('/')
// 4. Perform checks related to this fixture
expect(html).toContain('<div>ssr</div>')
})
})
// 5. Repeat
describe('csr', async () => { /* ... */ })
Having a playground Nuxt application to test your module when developing it is really useful. The module starter integrates one for that purpose.
You can test your module with other Nuxt applications (applications that are not part of your module repository) locally. To do so, you can use npm pack command, or your package manager equivalent, to create a tarball from your module. Then in your test project, you can add your module to package.json packages as: "my-module": "file:/path/to/tarball.tgz".
After that, you should be able to reference my-module like in any regular project.
With great power comes great responsibility. While modules are powerful, here are some best practices to keep in mind while authoring modules to keep applications performant and developer experience great.
As we've seen, Nuxt Modules can be asynchronous. For example, you may want to develop a module that needs fetching some API or calling an async function.
However, be careful with asynchronous behaviors as Nuxt will wait for your module to setup before going to the next module and starting the development server, build process, etc. Prefer deferring time-consuming logic to Nuxt hooks.
Nuxt Modules should provide an explicit prefix for any exposed configuration, plugin, API, composable, or component to avoid conflict with other modules and internals.
Ideally, you should prefix them with your module's name (e.g. if your module is called nuxt-foo, expose <FooButton> and useFooBar() and not <Button> and useBar()).
When your module needs to perform one-time setup tasks (like generating configuration files, setting up databases, or installing dependencies), use lifecycle hooks instead of running the logic in your main setup function.
import { addServerHandler, defineNuxtModule } from 'nuxt/kit'
import semver from 'semver'
export default defineNuxtModule({
meta: {
name: 'my-database-module',
version: '1.0.0',
},
async onInstall (nuxt) {
// One-time setup: create database schema, generate config files, etc.
await generateDatabaseConfig(nuxt.options.rootDir)
},
async onUpgrade (options, nuxt, previousVersion) {
// Handle version-specific migrations
if (semver.lt(previousVersion, '1.0.0')) {
await migrateLegacyData()
}
},
setup (options, nuxt) {
// Regular setup logic that runs on every build
addServerHandler({ /* ... */ })
},
})
This pattern prevents unnecessary work on every build and provides a better developer experience. See the lifecycle hooks documentation for more details.
Nuxt has first-class TypeScript integration for the best developer experience.
Exposing types and using TypeScript to develop modules benefits users even when not using TypeScript directly.
Nuxt relies on native ESM. Please read Native ES Modules for more information.
Consider documenting module usage in the readme file:
Linking to the integration website and documentation is always a good idea.
It's a good practice to make a minimal reproduction with your module and StackBlitz that you add to your module readme.
This not only provides potential users of your module a quick and easy way to experiment with the module but also an easy way for them to build minimal reproductions they can send you when they encounter issues.
Nuxt, Nuxt Kit, and other new toolings are made to have both forward and backward compatibility in mind.
Please use "X for Nuxt" instead of "X for Nuxt 3" to avoid fragmentation in the ecosystem and prefer using meta.compatibility to set Nuxt version constraints.
The module starter comes with a default set of tools and configurations (e.g. ESLint configuration). If you plan on open-sourcing your module, sticking with those defaults ensures your module shares a consistent coding style with other community modules out there, making it easier for others to contribute.
Nuxt Module ecosystem represents more than 15 million monthly NPM downloads and provides extended functionalities and integrations with all sort of tools. You can be part of this ecosystem!
Official modules are modules prefixed (scoped) with @nuxt/ (e.g. @nuxt/content). They are made and maintained actively by the Nuxt team. Like with the framework, contributions from the community are more than welcome to help make them better!
Community modules are modules prefixed (scoped) with @nuxtjs/ (e.g. @nuxtjs/tailwindcss). They are proven modules made and maintained by community members. Again, contributions are welcome from anyone.
Third-party and other community modules are modules (often) prefixed with nuxt-. Anyone can make them, using this prefix allows these modules to be discoverable on npm. This is the best starting point to draft and try an idea!
Private or personal modules are modules made for your own use case or company. They don't need to follow any naming rules to work with Nuxt and are often seen scoped under an npm organization (e.g. @my-company/nuxt-auth)
Any community modules are welcome to be listed on the module list. To be listed, open an issue in the nuxt/modules repository. The Nuxt team can help you to apply best practices before listing.
nuxt-modules and @nuxtjs/By moving your modules to nuxt-modules, there is always someone else to help, and this way, we can join forces to make one perfect solution.
If you have an already published and working module, and want to transfer it to nuxt-modules, open an issue in nuxt/modules.
By joining nuxt-modules we can rename your community module under the @nuxtjs/ scope and provide a subdomain (e.g. my-module.nuxtjs.org) for its documentation.