2

In Vue.js simply we can include axios as our deafault prototype for Vue.js and append local storage token to a default axios authorization header in the Vue main.js file .

As follows:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

Vue.config.productionTip = false

Vue.prototype.$http = axios;
const token = localStorage.getItem("token");
if(token){
  Vue.prototype.$http.defaults.headers.common['Authorization'] = token;
}

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

My question is how to set axios as a default prototype for Nuxt.js and append local storage token to a default axios authorization header inside the Nuxt.config.js File

kissu
  • 40,416
  • 14
  • 65
  • 133

1 Answers1

2

Not sure that the prototype is the way to go usually.

I do recommend this one for Nuxt Install nuxt/axios with
yarn add @nuxtjs/axios

Then, go to your Nuxt configuration
nuxt.config.js

plugins: ['@/plugins/nuxt-axios.js'],
modules: ['@nuxtjs/axios'],

And set the configuration to your axios as you wish
/plugins/nuxt-axios.js

export default ({ $axios }, $config: { authorizationToken }) => {
  $axios.defaults.headers.Authorization = authorizationToken
}

Or directly in the configuration file nuxt.config.js

axios: {
  headers: {
    Authorization: process.env.TOKEN,
  },
},

If you wish more info with the env variables, you can check this one: https://stackoverflow.com/a/67705541/8816585

kissu
  • 40,416
  • 14
  • 65
  • 133