The plugins directory contains JavaScript plugins that you want to run before instantiating the root Vue.js Application. This is the place to add Vue plugins and to inject functions or constants. Every time you need to use Vue.use(), you should create a file in plugins/ and add its path to plugins in nuxt.config.js.

You may want to use external packages/modules in your application (one great example is axios) for making HTTP requests for both server and client.

First, install it via npm or Yarn.

  1. npm install @nuxtjs/axios

You can configure for example the axios interceptors to react on possible errors from your API calls across the application. In this example we redirect the user to a custom error page called sorry when we get a 500 status error from our API.

plugins/axios.js

  1. export default function ({ $axios, redirect }) {
  2. $axios.onError(error => {
  3. if (error.response.status === 500) {
  4. redirect('/sorry')
  5. }
  6. })
  7. }

Last but not least, add the module and the newly created plugin to the project configuration.

nuxt.config.js

  1. module.exports = {
  2. modules: ['@nuxtjs/axios'],
  3. plugins: ['~/plugins/axios.js']
  4. }

Then we can use it directly in your page components:

pages/index.vue

  1. <template>
  2. <h1>{{ post.title }}</h1>
  3. </template>
  4. <script>
  5. export default {
  6. async asyncData ({ $axios, params }) {
  7. const post = await $axios.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
  8. return { post }
  9. }
  10. }
  11. </script>

Another way to use axios without installing the module is by importing axios direct in the <script> tag.

pages/index.vue

  1. import axios from 'axios'
  2. export default {
  3. async asyncData ({ params }) {
  4. const { data: post } = await axios.get(`https://api.nuxtjs.dev/posts/${params.id}`)
  5. return { post }
  6. }
  7. }

If you get an Cannot use import statement outside a module error, you may need to add your package to the build > transpile option in nuxt.config.js for webpack loader to make your plugin available.

nuxt.config.js

Vue Plugins

First we need to install it

  1. yarn add v-tooltip
  1. npm install v-tooltip

Then we create the file plugins/vue-tooltip.js

plugins/vue-tooltip.js

  1. import Vue from 'vue'
  2. import VTooltip from 'v-tooltip'
  3. Vue.use(VTooltip)

Then we add the file path inside the plugins key of our nuxt.config.js. The plugins property lets you add Vue.js plugins easily to your main application. All the paths defined in the plugins property will be imported before initializing the main application.

nuxt.config.js

  1. export default {
  2. plugins: ['~/plugins/vue-tooltip.js']
  3. }

If the plugin is located in node_modules and exports an ES6 module, you may need to add it to the transpile build option:

nuxt.config.js

  1. module.exports = {
  2. build: {
  3. transpile: ['vue-tooltip']
  4. }
  5. }

You can refer to the configuration build docs for more build options.

Some plugins might work only in the browser because they lack SSR support.

If a plugin is assumed to be run only on client or server side, .client.js or .server.js can be applied as an extension of the plugin file. The file will be automatically included only on the respective (client or server) side.

nuxt.config.js

You can also use the object syntax with the mode property ('client' or 'server') in plugins.

nuxt.config.js

  1. export default {
  2. plugins: [
  3. { src: '~/plugins/both-sides.js' },
  4. { src: '~/plugins/client-only.js', mode: 'client' }, // only on client side
  5. { src: '~/plugins/server-only.js', mode: 'server' } // only on server side
  6. ]
  7. }

Inject in $root & context

Sometimes you want to make functions or values available across your app. You can inject those variables into Vue instances (client side), the context (server side) and even in the Vuex store. It is a convention to prefix those functions with a $.

plugins - 图3

It is important to know that in any Vue instance lifecycle, only beforeCreate and hooks are called both, from client-side and server-side. All other hooks are called only from the client-side.

plugins/hello.js

  1. export default ({ app }, inject) => {
  2. // Inject $hello(msg) in Vue, context and store.
  3. inject('hello', msg => console.log(`Hello ${msg}!`))

nuxt.config.js

  1. export default {
  2. plugins: ['~/plugins/hello.js']
  3. }

Now $hello service can be accessed from context and this in pages, components, plugins, and store actions.

example-component.vue

  1. export default {
  2. mounted() {
  3. this.$hello('mounted')
  4. // will console.log 'Hello mounted!'
  5. },
  6. asyncData({ app, $hello }) {
  7. $hello('asyncData')
  8. // If using Nuxt <= 2.12, use 👇
  9. app.$hello('asyncData')
  10. }
  11. }

store/index.js

  1. export const state = () => ({
  2. someValue: ''
  3. })
  4. export const actions = {
  5. setSomeValueToWhatever({ commit }) {
  6. this.$hello('store action')
  7. const newValue = 'whatever'
  8. commit('changeSomeValue', newValue)
  9. }
  10. }

Don’t use Vue.use(), Vue.component(), and globally, don’t plug anything in Vue inside this function, dedicated to Nuxt injection. It will cause memory leak on server-side.

You may want to extend plugins or change the plugins order created by Nuxt.js. This function accepts an array of objects and should return an array of plugin objects.

Example of changing plugins order:

nuxt.config.js

Global mixins

Global mixins can be easily added with Nuxt plugins but can cause trouble and memory leaks when not handled correctly. Whenever you add a global mixin to your application, you should use a flag to avoid registering it multiple times:

plugins/my-mixin-plugin.js

  1. import Vue from "vue"
  2. // Make sure to pick a unique name for the flag
  3. // so it won't conflict with any other mixin.
  4. if (!Vue.__my_mixin__) {
  5. Vue.__my_mixin__ = true
  6. Vue.mixin({ ... }) // Set up your mixin then