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

Feb 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 pluginsexport 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)}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.