Nuxt Init/Entry via plugins (main.js of Vue)

February 20, 2020
Fetch app configuration data before app render

You need to setup a plugin for initialization.

Edit nuxt.config.js.

export default {
  plugins: [
    '~/plugins/init'
  ]
}

You can setup run specific code on client and server

export default {
  plugins: [
    '~/plugins/init', // run on both client and server
    { src: '~/plugins/init-client', mode: 'client' },
    { src: '~/plugins/init-server', mode: 'server' }
  ]
}

Edit plugins/init.js.

import Vue from 'vue'

if (process.server) {
    // do something

    if (process.static) {
        // do something
    }
}

if (process.client) {
    // do something
}

// Vue.prototype.$hello = ...

// OPTIONAL: access other plugins
export default sync ({ app, $axios, store }, inject) => {
  // access object injected by other plugins
  // app.$test.ping()

  // inject something
  // inject('hello', ...)

  // fetch configuration data before render
  let data = null
  if (process.server) { // read local file if server
    const fs = require('fs')
    data = JSON.parse(fs.readFileSync(`static/data/config.json`, 'utf8'))
  }
  else if (process.client) { // ajax fetch if client
    data = await $axios.get(`/data/config.json`)
  }
  // commit to vuex store
  store.commit('config', data)
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.