new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Nuxt · Guide · all subjects

plugins

39 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Plugins directory auto-registration

Nuxt automatically reads and loads files in the app/plugins/ directory at the creation of the Vue application. All plugins inside are auto-registered; you don't need to add them to nuxt.config separately.

Plugin file registration rules

Only files at the top level of the plugins directory or index files within any subdirectories are auto-registered as plugins. For example, in a plugins/ directory structure with foo.ts at the top level and bar/ subdirectory containing baz.ts, foz.vue, and index.ts, only foo.ts and bar/index.ts would be registered. Files in subdirectories like bar/baz.ts and bar/foz.vue are not scanned.

Register plugins in subdirectories via nuxt.config

To add plugins in subdirectories, use the plugins option in nuxt.config.ts. For example: export default defineNuxtConfig({ plugins: ['~/plugins/bar/baz', '~/plugins/bar/foz'] })

Plugin client and server suffixes

You can use .server or .client suffix in the plugin file name to load a plugin only on the server or client side.

Basic plugin structure

The only argument passed to a plugin is nuxtApp. A basic plugin exports a default function defined with defineNuxtPlugin that receives nuxtApp as its argument: export default defineNuxtPlugin((nuxtApp) => { // Plugin code })

Object syntax plugin definition

Plugins can be defined using object syntax for advanced use cases. The object has these properties: name (string), enforce ('pre' or 'post'), setup (function), hooks (object for registering Nuxt app runtime hooks), and env (object with islands property). Example: export default defineNuxtPlugin({ name: 'my-plugin', enforce: 'pre', async setup(nuxtApp) { }, hooks: { 'app:created'() { } }, env: { islands: true } })

Object syntax plugin properties are statically analyzed

When using object-syntax for plugins, the properties are statically analyzed to produce a more optimized build, so they should not be defined at runtime. For example, setting enforce: import.meta.server ? 'pre' : 'post' would defeat optimization. Nuxt statically pre-loads hook listeners when using object-syntax.

Control plugin registration order with numbering

Plugin registration order can be controlled by prefixing file names with alphabetical numbering, such as 01.myPlugin.ts and 02.myOtherPlugin.ts. In this case, 02.myOtherPlugin.ts would be able to access anything injected by 01.myPlugin.ts. Note that filenames are sorted as strings, so 10.myPlugin.ts would come before 2.myOtherPlugin.ts, which is why single digit numbers should be prefixed with 0.

Parallel plugins loading

By default, Nuxt loads plugins sequentially. To make a plugin load in parallel, define it with parallel: true in the object syntax. This allows the next plugin to be executed immediately without waiting for the current plugin to finish: export default defineNuxtPlugin({ name: 'my-plugin', parallel: true, async setup(nuxtApp) { } })

Plugin dependencies with dependsOn

If a plugin needs to wait for another plugin before it runs, add the plugin's name to the dependsOn array: export default defineNuxtPlugin({ name: 'depends-on-my-plugin', dependsOn: ['my-plugin'], async setup(nuxtApp) { } })

Composables in plugins limitation - plugin order dependency

If a composable depends on another plugin registered later, it might not work because plugins are called sequentially before everything else. A composable might depend on a plugin that has not been called yet.

Composables in plugins limitation - Vue.js lifecycle

Composables that depend on the Vue.js lifecycle won't work in plugins. Vue.js composables are bound to the current component instance while plugins are only bound to the nuxtApp instance.

Provide helpers from plugins

To provide a helper on the NuxtApp instance, return it from the plugin under a provide key: export default defineNuxtPlugin(() => { return { provide: { hello: (msg: string) => `Hello ${msg}!` } } }). Helpers are then accessible via useNuxtApp() as $hello.

Use composables instead of plugin helpers

It is highly recommended to use composables instead of providing helpers via plugins to avoid polluting the global namespace and keep the main bundle entry small.

Ref and computed in plugin provides not unwrapped in templates

If a plugin provides a ref or computed value, it will not be unwrapped in a component template. This is due to how Vue works with refs that aren't top-level to the template.

Plugin helper typing with declaration

To type provided helpers from plugins, declare them in an index.d.ts file using declare module with NuxtApp and ComponentCustomProperties interfaces: declare module '#app' { interface NuxtApp { $hello(msg: string): string } } and declare module 'vue' { interface ComponentCustomProperties { $hello(msg: string): string } }

Register Vue plugins in Nuxt plugins

Vue plugins like vue-gtag can be used in Nuxt by creating a Nuxt plugin that registers them: export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(VueGtag, { property: { id: 'GA_MEASUREMENT_ID' } }) })

Register Vue directives in plugins

Custom Vue directives can be registered in a plugin using nuxtApp.vueApp.directive: export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.directive('focus', { mounted(el) { el.focus() }, getSSRProps(binding, vnode) { return {} } }) })

Vue directive registration on both client and server

Custom Vue directives must be registered on both client and server side unless they are only used when rendering one side. If a directive only makes sense on client side, move it to ~/plugins/my-directive.client.ts and provide a 'stub' directive for the server in ~/plugins/my-directive.server.ts.

App plugins execution on server

The Vue and Nuxt instances are created first. Afterward, Nuxt executes its app plugins, which includes built-in plugins such as Vue Router and unhead, and custom plugins located in the app/plugins/ directory, including those without a suffix (e.g., myPlugin.ts) and those with the .server suffix (e.g., myServerPlugin.server.ts). Plugins execute in a specific order and may have dependencies on one another. After app plugins are initialized, Nuxt calls the app:created hook.

App plugins execution on client

On the client side, app plugins are executed, which includes both built-in and custom plugins. Custom plugins in the app/plugins/ directory, such as those without a suffix (e.g., myPlugin.ts) and with the .client suffix (e.g., myClientPlugin.client.ts), are executed on the client side. After this step, Nuxt calls the app:created hook.

Plugins run during hydration phase

Plugins in Nuxt run during the hydration phase. Inefficient plugin setups can block rendering and degrade user experience.

Large number of plugins cause performance issues

A large number of plugins can cause performance issues, especially if they require expensive computations or take too long to initialize.

Use composition over plugins when possible

Many utilities and composables can be used directly without the need for a plugin. Favoring composition over plugins keeps your project lightweight and improves maintainability.

Plugins load synchronously by default

By default, all plugins in Nuxt load synchronously.

Use parallel: true for async plugins

When defining asynchronous plugins, setting parallel: true allows multiple plugins to load concurrently, improving performance by preventing blocking operations.

Plugins extend application with functionality

Plugins in Nuxt allow you to extend your application with additional functionality.

Overusing plugins performance problem

A large number of plugins can cause performance issues, especially if they require expensive computations or long initialization times. Since plugins run during the hydration phase, inefficient setups can block rendering and degrade user experience. Solution: inspect plugins and implement some as composables or utility functions instead.

Creating custom $fetch instance with Nuxt plugin

You can create a custom $fetch instance using a Nuxt plugin by calling $fetch.create() with configuration options. The custom instance can then be provided to the Nuxt app and used directly with useAsyncData or passed to createUseFetch.

Custom $fetch plugin example

export default defineNuxtPlugin((nuxtApp) => { const { session } = useUserSession() const api = $fetch.create({ baseURL: 'https://api.nuxt.com', onRequest ({ request, options, error }) { if (session.value?.token) { options.headers.set('Authorization', `Bearer ${session.value?.token}`) } }, async onResponseError ({ response }) { if (response.status === 401) { await nuxtApp.runWithContext(() => navigateTo('/login')) } }, }) return { provide: { api, }, } }) This plugin creates a custom $fetch instance that is provided to the app as $api.

Extend NuxtApp Interface and Runtime Hooks

To extend the nuxtApp interface and hook into different stages or access contexts, use Nuxt Plugins. Plugins can interact with the Runtime Core.

Using runtime config in plugins

Runtime config can be accessed in custom plugins by calling useRuntimeConfig() inside a defineNuxtPlugin function, allowing plugins to read configuration values during initialization.

App Hooks usage in plugins

App Hooks are runtime hooks mainly used by Nuxt Plugins to hook into the rendering lifecycle. They can also be used in Vue composables. App hooks are accessed via nuxtApp.hook() in a plugin. Example: export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('page:start', () => { /* your code goes here */ }) })

Plugins receive nuxtApp as first argument

Plugins automatically receive nuxtApp as the first argument for convenience, so you do not need to call useNuxtApp() inside plugin functions.

Provide helpers via nuxtApp

You can provide helpers to be usable across all composables and the application by calling nuxtApp.provide(key, value). For example, nuxtApp.provide('hello', name => `Hello ${name}!`) makes the helper accessible as nuxtApp.$hello('name'). This usually happens within a Nuxt plugin, and can also be done by returning an object with a provide key in plugins.

Providing helpers via nuxtApp example

Example of providing helpers using nuxtApp: ```ts const nuxtApp = useNuxtApp() nuxtApp.provide('hello', name => `Hello ${name}!`) console.log(nuxtApp.$hello('name')) // Prints "Hello name!" ```

useNuxtApp.provide() method for creating plugins

The provide method on nuxtApp accepts name and value parameters. It is used to create Nuxt plugins to make values and helper methods available across all composables and components in the application. Example: nuxtApp.provide('hello', name => `Hello ${name}!`) makes $hello available on the nuxtApp context.

useNuxtApp.hook() method for customizing runtime lifecycle

The hook method on nuxtApp allows you to hook into the rendering lifecycle at a specific point. It accepts name and callback parameters. This method is useful for adding custom logic and is mostly used when creating Nuxt plugins. Available runtime hooks are documented in Runtime Hooks.

useNuxtApp.callHook() method for executing hooks

The callHook method returns a promise when called with any of the existing hooks. Example: await nuxtApp.callHook('my-plugin:init')

Give your agent this brain