5

I use NuxtJS 2, and I need to have 2 or more axios instances with different configs.

In VueJS / JS classic, I can just create a new instance of axios:

var axiosElasticSearch = axios.create({
  baseURL: 'https://elastic.com/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

But in Nuxt, they apply their own config to handle this, because of the SSR layer.

In my Nuxt config, I have this :

axios: {
    baseUrl: process.env.API_URL,
    browserBaseUrl: process.env.BROWSER_API_URL,
    withCredentials: true,
    headers: {
      common: {
        Accept: 'application/json',
        Authorization: 'Bearer ' + process.env.API_TOKEN
      }
    }
  },

And then, I can inject it easily.

Is it possible to manage it in Nuxt? I looked at proxy option, but I don't think it's what I want.

kissu
  • 40,416
  • 14
  • 65
  • 133
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
  • This can maybe help: https://github.com/nuxt-community/axios-module/issues/286#issue-500836431 – kissu May 27 '21 at 08:37

1 Answers1

12

nuxt/axios allows creating new Axios instances with $axios.create, which takes the Axios config from nuxt.config.js into account.

For example, you could create a Nuxt plugin that injects a new Axios instance into the root context:

// ~/plugin/api.js
export default function ({ $axios }, inject) {
  // Create a custom axios instance
  const api = $axios.create({
    headers: {
      common: {
        Accept: 'text/plain, */*'
      }
    }
  })

  // Set baseURL to something different
  api.setBaseURL('https://my_api.com')

  // Inject to context as $api
  inject('api', api)
}

And configure your Nuxt app to use it:

// nuxt.config.js
export default {
  plugins: ['~/plugins/api.js']
}

Then your component could use the new Axios instance:

// MyComponent.vue
export default {
  fetch() {
    this.$api.get(...)
  },
  asyncData({ $api }) {
    $api.get(...)
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307