Plugins
Nuxt Plugins System
Plugins are a way to extend your Nuxt application with global functionality. They run before the app is created, allowing you to register Vue plugins, add global components, provide utilities, and more.
Creating a Plugin
Plugins are defined in the plugins/ directory:
// plugins/my-plugin.ts
export default defineNuxtPlugin((nuxtApp) => {
// Plugin code here
})
Client vs Server Plugins
You can create plugins that run only on client or server:
plugins/
├── analytics.client.ts → Only runs on client
├── logger.server.ts → Only runs on server
└── my-plugin.ts → Runs on both
Or use the plugin API:
export default defineNuxtPlugin({
name: 'my-plugin',
enforce: 'pre', // 'pre' | 'default' | 'post'
hooks: {
'app:created': function () {
// Hook into app lifecycle
}
},
setup(nuxtApp) {
// Plugin logic
}
})
Provide/Inject Pattern
Plugins commonly use provide to make utilities available throughout the app:
export default defineNuxtPlugin(() => {
return {
provide: {
hello: (name: string) => `Hello ${name}!`
}
}
})
Usage in components:
<script setup>
const { $hello } = useNuxtApp()
console.log($hello('World')) // "Hello World!"
</script>
Plugin Order
Plugins run in alphabetical order by default. You can control the order:
- Use numeric prefixes:
01.first.ts,02.second.ts - Use the
enforceoption:'pre','default', or'post'
Challenge
Create an analytics plugin that tracks page views:
- Create
plugins/analytics.client.tsthat:- Provides a
$trackfunction - The function should log events to the console (simulating analytics)
- Add a router hook to track page views automatically
- Provides a
- In
app.vue:- Use the
$trackfunction to manually track a button click - Display the tracked events count
- Use the
Pitfall: Plugin execution order matters! If plugin B depends on plugin A, make sure A runs first using numeric prefixes or enforce: 'pre'.
Tip: Use .client.ts suffix for plugins that use browser APIs like window or localStorage.
If you get stuck, you can check the solution by clicking the button below.
Plugins are essential for adding global functionality, integrating third-party libraries, and extending Nuxt's capabilities. Use them for Vue plugins, composables that need early initialization, or app-wide utilities.