Plugins
A plugin is a file that Nuxt runs once when the app starts, before the first page is shown. Plugins connect Vue libraries, register directives and add helpers available across the whole app. They live in the app/plugins/ folder and are registered automatically.
The first plugin
npx nuxi add plugin excerptThe command creates app/plugins/excerpt.ts. Replace its content:
// app/plugins/excerpt.ts
export default defineNuxtPlugin(() => {
return {
provide: {
excerpt: (text: string, length = 100) =>
text.length > length ? text.slice(0, length) + '…' : text
}
}
})Everything inside provide becomes available to the whole app with a $ prefix. Here it is the $excerpt function that shortens long text for a preview.
Using it
In a template the helper is available right away:
<!-- app/components/PostCard.vue -->
<template>
<article class="post-card">
<h3>{{ post.title }}</h3>
<p>{{ $excerpt(post.text, 60) }}</p>
</article>
</template>The cards on /posts show at most 60 characters of text and an ellipsis. In <script setup> you get the helper through useNuxtApp():
<!-- app/components/PostCard.vue -->
<script setup lang="ts">
const { $excerpt } = useNuxtApp()
const preview = $excerpt('A very long post text', 10)
</script>A directive
A plugin receives the nuxtApp object, and through it the Vue app itself. Register a directive that puts the cursor into a field:
// app/plugins/focus.ts
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.directive('focus', {
mounted(el: HTMLElement) {
el.focus()
}
})
})Now any template can use <input v-focus>, for example in the title field of the new post form. After the page opens, the cursor is in that field. Libraries written for Vue are connected the same way, through nuxtApp.vueApp.use(...).
Browser only or server only
| File name | Where it runs |
|---|---|
app/plugins/excerpt.ts | On the server and in the browser |
app/plugins/analytics.client.ts | Only in the browser |
app/plugins/logger.server.ts | Only on the server |
The .client suffix is needed when a plugin touches window or loads a library that works only in the browser.
Order
Plugins run in the alphabetical order of their file names. If one plugin depends on another, add numbers to the names: 01.api.ts, 02.excerpt.ts.
Plugin or composable
If code is needed only by some components, make it a composable: it runs only where it is called. A plugin runs on every app start, so every unnecessary plugin slows down loading.
Common mistake
A file in a subfolder, such as app/plugins/helpers/excerpt.ts, is not registered, and the template fails with $excerpt is not a function. Nuxt picks up only the top-level files of app/plugins/ and index.ts files in subfolders. Keep plugins directly in the folder.