Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 32 ยท Plugins, modules and layers

Plugins and Nuxt Modules

Learn how Nuxt plugins run before your app, how provide creates $helpers, what modules add to a project, and how to write a tiny module with hooks.

Sooner or later every app needs code that runs once, early, and affects everything: set up an analytics client, register a custom directive, give every component a $api helper, or attach error reporting. In Nuxt that code lives in plugins. When the same setup is useful in many projects, you package it as a module, a piece of code that runs at build time and can add plugins, components, composables, routes and configuration to the project that installs it.

This lesson explains both. You will see how Nuxt finds and orders plugins, what provide really does, which official and community modules most projects use, and how a small module is written. Real Nuxt cannot run on this site, so every Nuxt file below is read-only. The runnable examples are plain JavaScript stand-ins that copy the mechanism (ordering, injection, hooks) in a few dozen lines, and each says what it simplifies.

Plugins versus modules

Plugin Runs while the app starts, on the server, the client or both.
Module Runs at build time and can change the whole project.
Together A module usually ships a plugin, plus components and config.

Plugins shape the running app. Modules shape the project.

1 / 2

Your first plugin

Every file directly inside the plugins/ directory (and every index file one folder down) is loaded automatically. You do not list them anywhere. A plugin exports the result of defineNuxtPlugin, which receives the Nuxt app object, commonly named nuxtApp:

TypeScript
// plugins/format.ts (read-only)
export default defineNuxtPlugin(() => {
  const money = (cents: number) =>
    new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(cents / 100);

  return {
    provide: {
      money,
    },
  };
});

Whatever you put under provide becomes available with a $ prefix. Here the helper is reachable in three places:

VUE
<script setup lang="ts">
// read-only
const { $money } = useNuxtApp();
const label = $money(1999);
</script>

<template>
  <p>{{ label }} or {{ $money(500) }}</p>
</template>

In the template you can use $money directly. In script code and composables, get it from useNuxtApp(). If you use TypeScript, Nuxt picks up the type from the returned object, so $money(1999) is checked.

Two practical rules keep plugins healthy:

  • Do only what must happen at startup. A pure helper function usually belongs in utils/ or composables/, which are auto-imported (see Auto-imports) and cost nothing at startup. A plugin earns its place when it needs the nuxtApp, needs to register something on the Vue app, or needs to run before the first render.
  • Keep them quick. Plugins run before the page renders, so a slow plugin delays every visitor. If a plugin returns a promise, Nuxt waits for it.

Where a plugin runs and in which order

Nuxt renders the same app on the server and in the browser (see Rendering modes), so a plugin may run in both places. Control that with the file name:

File name Runs
plugins/analytics.client.ts Only in the browser
plugins/seo.server.ts Only on the server
plugins/format.ts In both

Browser-only code such as one that touches window belongs in a .client plugin. Hydration and SSR pitfalls shows why.

Order matters when one plugin needs another. By default Nuxt sorts plugin files alphabetically by file name. The long-standing convention is to prefix the files with numbers:

Terminal
# read-only
plugins/
  01.error-reporting.ts
  02.api.ts
  03.analytics.client.ts

A more explicit way is the object syntax, where a plugin names itself and lists what it needs:

TypeScript
// plugins/api.ts (read-only)
export default defineNuxtPlugin({
  name: "api",
  dependsOn: ["error-reporting"],
  async setup(nuxtApp) {
    const config = useRuntimeConfig();
    const api = $fetch.create({ baseURL: config.public.apiBase });
    return { provide: { api } };
  },
  hooks: {
    "app:created"() {
      // runs after the Vue app has been created
    },
  },
});

dependsOn makes Nuxt wait for the named plugin to finish before starting this one. The hooks object is a shortcut for registering hooks, covered next.

A stand-in for the plugin system

The example below is not Nuxt's loader. It sorts file names, honours the .client and .server suffixes, turns provide into $names, and reports a clash if two plugins provide the same name. It leaves out dependsOn, parallel plugins and everything Vue-related.

JS A tiny plugin loader: order, suffixes and provide

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The server run skips the analytics plugin and keeps the SEO plugin, the browser run does the opposite, and both run 01.config before 02.api, which is why the API helper can read app.config. Rename 01.config.js to 09.config.js and the helper would print GET undefined/users, because it copies the base address while it is being set up: the numeric prefix is doing real work.

Hooks: reacting to what Nuxt does

Nuxt announces many moments in the life of an app through hooks: the Vue app was created, the page finished loading, the app is mounted, an error happened. A plugin subscribes with nuxtApp.hook(name, callback):

TypeScript
// plugins/page-timer.client.ts (read-only)
export default defineNuxtPlugin((nuxtApp) => {
  let start = 0;
  nuxtApp.hook("page:start", () => {
    start = performance.now();
  });
  nuxtApp.hook("page:finish", () => {
    console.log(`navigation took ${Math.round(performance.now() - start)} ms`);
  });
});

You can also fire your own hooks with nuxtApp.callHook, which lets plugins talk to each other without importing each other. Hooks exist at two levels: runtime hooks like the ones above (they belong to the running app), and build-time hooks that modules use while Nuxt is preparing the project.

Modules: packaged build-time extensions

Install a module with your package manager and list it in nuxt.config.ts:

TypeScript
// nuxt.config.ts (read-only)
export default defineNuxtConfig({
  modules: ["@nuxt/image", "@nuxt/content", "@nuxtjs/i18n"],
  image: {
    quality: 80,
  },
});

The module's own settings usually sit under a key that matches its name (image, content, i18n). A module can register plugins and components, add auto-imported composables, extend routes, change the build, and add server handlers, all without you copying files into your project. Some modules that many projects use:

Need Module
Component library @nuxt/ui
Markdown content as pages @nuxt/content
Optimized images (<NuxtImg>) @nuxt/image
Translations and locale routes @nuxtjs/i18n
Fonts @nuxt/fonts
Sign-in and sessions nuxt-auth-utils and others
Security headers and rate limiting nuxt-security

Treat that table as a starting point, not a recommendation: check each module's page in the Nuxt module list for the Nuxt versions it supports and how recently it was released. Every module you add is code that runs in your build and, often, in your app.

Before writing a plugin that wraps a library, look for a module for it. A good module also handles server-side rendering details (such as keeping state per request) that a quick plugin often forgets.

Writing a tiny module

A module is a function that receives its options and the Nuxt instance. You build it with defineNuxtModule from @nuxt/kit. Nuxt also auto-registers any module found in a top-level modules/ directory of your project, which is the easiest way to try one:

TypeScript
// modules/hello/index.ts (read-only)
import { defineNuxtModule, addPlugin, addImports, createResolver } from "@nuxt/kit";

export default defineNuxtModule<{ greeting: string }>({
  meta: {
    name: "hello",
    configKey: "hello",
  },
  defaults: {
    greeting: "Hello",
  },
  setup(options, nuxt) {
    const { resolve } = createResolver(import.meta.url);

    nuxt.options.runtimeConfig.public.greeting = options.greeting;
    addPlugin(resolve("./runtime/plugin"));
    addImports({ name: "useGreeting", from: resolve("./runtime/useGreeting") });

    nuxt.hook("ready", () => {
      console.log("hello module is ready");
    });
  },
});

Reading it from the top:

  • meta.configKey means users configure it with hello: { greeting: "Hi" } in nuxt.config.ts. Their values are merged over defaults before setup runs.
  • createResolver turns paths relative to the module file into absolute ones, so the module works wherever it is installed.
  • addPlugin registers a plugin file (kept in a runtime/ folder, because that code ships to the app) as if it were in the user's plugins/ directory, and addImports makes useGreeting auto-imported.
  • The setup function itself runs at build time, in Node. Only the files you register run in the app.

That last point is the most common source of confusion: code in setup can use Node features but cannot touch the browser, and code in runtime/ is app code that cannot use Node.

A stand-in for a module

This simplified kit lets a module change the options, register plugins and subscribe to a hook. Real Nuxt does far more (merging user options with defaults recursively, type generation, ordering), so treat it as an illustration of the idea only.

JS A tiny module system

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first run uses the module's default greeting. The second shows the user's hello options overriding it, and in both runs the module wrote the final value into the public runtime config and registered a plugin that created $greet.

Common mistakes

  • Putting browser-only code in a shared plugin. Use the .client suffix, or guard the code.
  • Sharing mutable state at module level inside a plugin. The server handles many visitors in one process, so shared variables leak between requests. Use useState or per-request values (see State with useState and Pinia).
  • Reaching for a plugin when a composable would do. If nothing needs the nuxtApp at startup, prefer a composable.
  • Forgetting ordering. If plugin B reads what plugin A provides, name them so A sorts first or declare dependsOn.
  • Adding many modules without checking them. Each one adds build time, bundle size and a dependency to maintain.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You return { provide: { api } } from a plugin. How do you use it in a component's script?

    Provided values get a dollar-sign prefix and are read from the Nuxt app object, which useNuxtApp() returns. In a template you can write $api directly.
  2. 2. Which file runs only in the browser?

    The .client suffix limits a plugin to the browser and .server limits it to the server. A name without a suffix runs in both places.
  3. 3. When does the setup function of a module (defineNuxtModule) run?

    Module setup runs in Node while Nuxt is starting or building. It registers things for the app, such as plugins and imports, but is not itself part of the running app.
  4. 4. Two plugins must run in a fixed order. What is the simplest way to guarantee it?

    Plugins load alphabetically by file name, so numeric prefixes control the order. The object syntax with name and dependsOn states the requirement explicitly.

Summary

  • Files in plugins/ load automatically; defineNuxtPlugin receives the Nuxt app, and a returned provide object creates $name helpers.
  • .client and .server suffixes choose where a plugin runs; file names (often number-prefixed) or dependsOn choose the order.
  • Hooks let plugins react to app events, and callHook lets them talk to each other.
  • Modules are listed in modules in nuxt.config.ts, are configured under their own key, and extend the project at build time.
  • A custom module uses defineNuxtModule with meta, defaults and setup, and registers runtime files with helpers such as addPlugin and addImports.
  • Choose a composable for plain helpers, a plugin for startup work, and a module for reusable project-wide setup.

Next: Layers and code organization