Authoring Nuxt Modules: Nuxt Kit and Publishing to NPM

Authoring Nuxt Modules: Nuxt Kit and Publishing to NPM

Learn to build, test, type, and publish Nuxt modules using Nuxt Kit, separating build-time definitions from runtime code and preparing packages for npm and the Nuxt registry.

Reza Baar

Reza Baar

December 1, 2026

Modules are how Nuxt gets extended. Almost every official feature, from image handling to content to the SEO stack, ships as a module, and when you need to package a cross-cutting concern for reuse across projects, a module is the right tool. In this post, we'll build a real one from start to finish: scaffold it, wire up type-safe options with Nuxt Kit, inject runtime code, expose types, add a server handler, and publish it to npm. This is written for people who already know their way around Nuxt and want the authoring workflow done properly.

When a Module Is the Right Tool

It's worth being clear on when you need a module versus a plugin, a composable, or a layer. A plugin runs at app startup and provides app-level injections. A composable is just a function. A layer shares config and files by extension. A module is build-time code: it runs while Nuxt is building, and it can do things the others can't, such as modifying the Nuxt config, registering plugins and components conditionally, generating files, hooking into the build lifecycle, and adding server handlers.

Reach for a module when you need to extend Nuxt itself rather than add a piece of app code. Analytics integrations, a design-system wrapper, a feature that registers components plus a plugin plus a server route, anything with options users configure in nuxt.config, those are module territory.

Scaffolding with the Module Template

Start from the official module starter rather than assembling the toolchain by hand. It wires up the build tooling, a playground app for development, and a test setup:

npm create nuxt -- -t module my-analytics

This gives you a project built around the Nuxt module builder, the build tool designed specifically for modules. It handles the thing that makes module builds tricky: a module ships two kinds of code that live in different environments and need different treatment. That distinction is the single most important concept in module authoring, so we'll come back to it.

The generated structure matters, so here's the shape:

my-analytics/
  src/
    module.ts          # the module definition (build-time code)
    runtime/           # code that runs in the user's app (runtime code)
      plugin.ts
      composables/
  playground/          # a Nuxt app for developing against the module
  test/
  package.json

Build-Time vs Runtime: The Core Distinction

This is the concept that trips up people who are otherwise comfortable with Nuxt. A module has two separate halves.

The module definition (src/module.ts) is build-time code. It runs in Node during the build, has access to the Nuxt instance, and is where you call Nuxt Kit utilities. It never runs in the browser.

The runtime directory (src/runtime/) is the code that ends up in the user's application: plugins, components, composables, server handlers. This code runs in the user's app context, on both server and client.

Here's why the distinction matters in practice: your module definition registers runtime files by path, it never imports them directly. Importing a runtime file into your module definition pulls app code into the build process where it doesn't belong, and it breaks. The two halves communicate through Kit utilities and resolved paths. Keep that boundary clean and most module bugs never happen.

The Module Definition

Every module is created with defineNuxtModule from Nuxt Kit. The object form gives you type hints, meta, and typed options:

// src/module.ts — the module definition, runs at build time
import { defineNuxtModule, createResolver, addPlugin } from '@nuxt/kit'

export interface ModuleOptions {
  apiKey: string
  enabled: boolean
  trackPageViews: boolean
}

export default defineNuxtModule<ModuleOptions>({
  meta: {
    name: 'my-analytics',
    configKey: 'analytics',
  },
  defaults: {
    apiKey: '',
    enabled: true,
    trackPageViews: true,
  },
  setup(options, nuxt) {
    // options is fully typed as ModuleOptions, merged with defaults
    if (!options.enabled) {
      return
    }

    const resolver = createResolver(import.meta.url)
    addPlugin(resolver.resolve('./runtime/plugin'))
  },
})

A few things here are worth calling out for anyone who's written a quick module before but not a careful one.

The meta block carries the module's identity. name is usually the npm package name, and configKey is the key users configure the module under in nuxt.config.

defaults are merged with the user's options before setup runs, so by the time you read options inside setup, it's the fully resolved configuration. You don't hand-merge defaults.

The defineNuxtModule<ModuleOptions> generic is what makes options typed inside setup and makes the user's nuxt.config entry type-checked. Export the ModuleOptions interface so consumers can reference it.

createResolver: Resolving Paths Correctly

createResolver(import.meta.url) is the utility you'll use in nearly every module. Your module's files sit at paths relative to the module itself, but the module runs inside the user's project, where a relative path resolves against the wrong base. createResolver creates a resolver anchored to your module's location, so resolver.resolve('./runtime/plugin') always points at your runtime file regardless of where the module is installed.

Always register runtime files through a resolver. Passing a bare relative string to a Kit utility is a common source of "works in the playground, breaks when published" bugs.

Injecting Runtime Code

With the boundary and the resolver understood, the actual injection is the easy part. Kit provides a utility for each kind of thing you'd add.

Plugins go in through addPlugin:

addPlugin(resolver.resolve('./runtime/plugin'))

Components through addComponent, which registers them as auto-imports. Prefix component names to avoid collisions with the user's own components:

// src/module.ts — register a component as an auto-import
import { addComponent, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url)

    addComponent({
      name: 'AnalyticsConsent', // auto-imported in the user's app
      filePath: resolver.resolve('./runtime/components/AnalyticsConsent.vue'),
    })
  },
})

Composables and utilities through addImports (single) or addImportsDir (a whole directory):

// src/module.ts — auto-import a composable from the runtime directory
import { addImports, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url)

    addImports({
      name: 'useAnalytics', // the export name
      from: resolver.resolve('./runtime/composables/useAnalytics'),
    })
  },
})

The pattern is consistent: the definition names a thing and points at a runtime file, and Kit handles the rest.

Passing Options to Runtime Code Through runtimeConfig

Here's where the build-time and runtime split becomes concrete. Your module reads options at build time, but your runtime plugin needs those values when it runs in the user's app. You can't close over them, because the two halves are separate bundles. The bridge is runtimeConfig.

Push your options into runtimeConfig in the module definition:

// src/module.ts — expose options to the runtime through runtimeConfig
import { defineNuxtModule, createResolver, addPlugin } from '@nuxt/kit'

export default defineNuxtModule<ModuleOptions>({
  meta: { name: 'my-analytics', configKey: 'analytics' },
  defaults: { apiKey: '', enabled: true, trackPageViews: true },
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url)

    // Public config is exposed to the client; keep secrets in the non-public root
    nuxt.options.runtimeConfig.public.analytics = {
      enabled: options.enabled,
      trackPageViews: options.trackPageViews,
    }

    addPlugin(resolver.resolve('./runtime/plugin'))
  },
})

Then the runtime plugin reads it back with useRuntimeConfig:

// src/runtime/plugin.ts — runtime code, runs in the user's app
import { defineNuxtPlugin, useRuntimeConfig } from '#app'

export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig().public.analytics

  if (config.trackPageViews) {
    // set up page-view tracking
  }
})

Mind the split between runtimeConfig.public and the non-public root. Anything under public is sent to the client. An API secret belongs in the non-public root (nuxt.options.runtimeConfig.analytics), where it stays server-only. Getting this wrong leaks secrets into the client bundle, so be deliberate about which values go where.

Exposing Types to the User's App

A module that ships runtime code should ship types for it too, so the user's editor understands the injected composables and config. addTypeTemplate generates a declaration file that Nuxt includes in the user's TypeScript project:

// src/module.ts — generate ambient types for the user's app
import { addTypeTemplate, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options, nuxt) {
    addTypeTemplate({
      filename: 'types/analytics.d.ts',
      getContents: () => `
declare module '#app' {
  interface NuxtApp {
    $analytics: {
      track: (event: string, data?: Record<string, unknown>) => void
    }
  }
}
export {}
`,
    })
  },
})

This is the kind of polish that separates a module people tolerate from one they enjoy. The injected helpers show up with full type information instead of any.

Adding a Server Handler

Modules aren't limited to client code. If yours needs a server endpoint, a tracking collector or a webhook receiver, register it with addServerHandler:

// src/module.ts — register a server route from the module
import { addServerHandler, createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  setup(options, nuxt) {
    const resolver = createResolver(import.meta.url)

    addServerHandler({
      route: '/api/analytics/collect',
      method: 'post',
      handler: resolver.resolve('./runtime/server/collect.post'),
    })
  },
})

The handler file lives in src/runtime/server/ and is written like any Nitro event handler. This is how a module ships a full-stack feature: components and a plugin on the client, an endpoint on the server, all from one install.

Hooking Into the Build and Lifecycle

Two capabilities are worth knowing for anything non-trivial.

Nuxt hooks let your module react to build events. Call nuxt.hook in setup to tap into the lifecycle, for example to adjust the Nitro config:

setup(options, nuxt) {
  nuxt.hook('nitro:config', (nitroConfig) => {
    nitroConfig.externals ||= {}
    // adjust Nitro as needed
  })
}

Module lifecycle hooks (onInstall and onUpgrade) run at install and version-change time rather than on every build. onInstall fires once, when the module is first added to a project, which suits one-time setup like generating a config file or printing a welcome message. onUpgrade runs when the module's version increases, once per bump, and receives the previous version so you can surface migration notes:

// src/module.ts — react to install and upgrades
export default defineNuxtModule<ModuleOptions>({
  meta: { name: 'my-analytics', configKey: 'analytics', version: '1.0.0' },
  async onInstall(nuxt) {
    console.log('Thanks for installing my-analytics. Set your apiKey to get started.')
  },
  async onUpgrade(inlineOptions, nuxt, previousVersion) {
    console.log(`Upgraded my-analytics from v${previousVersion}. Check the migration notes.`)
  },
  setup(options, nuxt) {
    // regular setup, runs on every build
  },
})

These rely on meta.version for the semver comparison, so set it when you use them. They're a clean way to improve the upgrade experience without forcing users to read a changelog they'll skip.

Declaring Module Dependencies

If your module depends on other modules, declare them with moduleDependencies rather than asking users to install and register them by hand. Nuxt resolves and installs them for you, and you can set a version constraint, mark one optional, or pass configuration overrides:

// src/module.ts — depend on another module, installed automatically
export default defineNuxtModule<ModuleOptions>({
  meta: { name: 'my-analytics', configKey: 'analytics' },
  moduleDependencies: {
    '@nuxt/image': {
      version: '>=1',
      optional: true,
    },
  },
  setup(options, nuxt) {
    // ...
  },
})

This keeps the install story to a single package for your users, even when your module builds on top of others.

Developing Against the Playground

The starter's playground/ directory is a real Nuxt app with your module pre-registered. This is where you develop. Run it and you get HMR against both the playground and your module source:

npm run dev

The playground's config references your module by its local path, so changes to src/ reflect immediately. Treat the playground as both your development harness and a living example of how the module is used.

Testing

The starter sets up the Nuxt test utilities, which let you spin up a real Nuxt app with your module applied and assert on the result. This is the right level to test a module: not the internals of your setup function, but the actual effect on a Nuxt app.

// test/basic.test.ts
import { describe, it, expect } from 'vitest'
import { setup, $fetch } from '@nuxt/test-utils/e2e'

describe('my-analytics', () => {
  it('registers the collect endpoint', async () => {
    await setup({ rootDir: './playground' })
    const res = await $fetch('/api/analytics/collect', { method: 'POST' })
    expect(res).toBeDefined()
  })
})

Testing the integration rather than the unit is what gives you confidence the module behaves correctly once installed, which is the only thing that matters to your users.

Preparing for Publication

Before publishing, the build tooling produces the distributable artifact. The starter's scripts handle this:

npm run prepack

The module builder compiles src/ into dist/, producing the build-time module and the runtime code with correct formats and type declarations. The reason to use the builder rather than a generic bundler is that it produces an artifact compatible across the Nuxt versions you support and handles the runtime code correctly so it works in the user's app environment.

Your package.json needs the right fields for Nuxt to recognize and load the module. The starter sets these up, but it helps to understand what they do:

{
  "name": "my-analytics",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/types.d.mts",
      "import": "./dist/module.mjs"
    }
  },
  "main": "./dist/module.mjs",
  "typesVersions": {
    "*": {
      ".": ["./dist/types.d.mts"]
    }
  },
  "files": ["dist"],
  "scripts": {
    "prepack": "nuxt-module-build build"
  },
  "dependencies": {
    "@nuxt/kit": "latest"
  },
  "devDependencies": {
    "@nuxt/module-builder": "latest"
  }
}

The details that matter: @nuxt/kit is a real dependency, since your published module imports from it at the user's build time, not a dev dependency. The exports map points at the compiled entry and its types. And files limits the published package to dist, so you're not shipping source and playground to every consumer.

Publishing to npm

With a clean build, publishing is the standard npm flow. Make sure you're logged in:

npm login

Then publish. For a first release of a scoped package, you'll want public access:

npm publish --access public

A couple of things are worth doing properly rather than skipping. Run npm pack first and inspect the tarball it produces; it shows exactly what will ship, and it's the fastest way to catch a misconfigured files field before it goes out. For versioning, use npm version patch|minor|major so the git tag and package.json stay in sync, and follow semver honestly, since consumers rely on your version to make upgrade decisions.

Once published, users install it and add it to their modules array:

npm install my-analytics
// nuxt.config.ts (the user's app)
export default defineNuxtConfig({
  modules: ['my-analytics'],
  analytics: {
    apiKey: process.env.ANALYTICS_KEY,
    trackPageViews: true,
  },
})

Because you set configKey: 'analytics' and exported typed options, their config is type-checked, and everything your module injects is available with full types.

Listing on the Nuxt Module Registry

One last step that's easy to miss. The Nuxt ecosystem has a module registry that powers module discovery on the Nuxt website. Getting listed means adding your module there with the metadata the registry displays: name, description, category, and compatibility. It's worth doing, since the official registry is a meaningful discovery channel, and a listing signals that your module is a real, maintained part of the ecosystem rather than a loose package.

Key Takeaways

  • A module is build-time code that extends Nuxt itself. Reach for it over a plugin or composable when you need to modify config, register things conditionally, or ship a full-stack feature
  • Scaffold with npm create nuxt -- -t module, which sets up the module builder, a playground, and tests
  • The core concept is the build-time (src/module.ts) versus runtime (src/runtime/) split. The definition registers runtime files by resolved path, never by direct import
  • Use defineNuxtModule with a typed ModuleOptions generic, meta, and defaults
  • Always resolve runtime paths with createResolver(import.meta.url)
  • Inject with addPlugin, addComponent, addImports, and addServerHandler, and bridge options to runtime through runtimeConfig, minding the public and secret split
  • Ship types with addTypeTemplate, improve upgrades with onInstall/onUpgrade, and pull in other modules with moduleDependencies
  • Build with the module builder, keep @nuxt/kit as a real dependency, publish with the standard npm flow, and list on the module registry

Conclusion

Authoring a Nuxt module comes down to respecting one boundary: build-time code that configures Nuxt, and runtime code that runs in the user's app, communicating through Kit utilities and runtimeConfig rather than direct imports. The rest, from typed options to injected components to a release, follows a consistent, well-supported pattern. Start from the module template, develop against the playground, test the integration, and publish with the builder, and you end up with a module that feels like a first-class part of the ecosystem.

I hope this post has been helpful. Please let me know if you have any questions or comments. Happy coding!

Ready to prove your Nuxt skills?

Get certified in Nuxt

More Nuxt articles

Keep learning Nuxt. Then get certified when you are ready.