Search code examples
vue.jsaxiosenvironment-variablesnuxt.jsdotenv

How to use env var for API in NuxtJS axios?


I have a working snippet

const response = await axios.get('http://example.com/categories')

But I want to refactor it by moving http://example.com to .env.

I made the following changes but successful

  1. .env contains http://example.com
  2. const response = await axios.get('/categories')
  3. In nuxt.config.js:
       publicRuntimeConfig: {
        axios: {
          baseURL: process.env.API_URL,
        },
      },

Result: It's trying to access http://localhost:3000/categories

UPDATE:

Thanks to @AmirhosseinShahbazi for his answer.

Besides his advice on fix, I have also changed nuxt.config.js

from

       publicRuntimeConfig: {
        axios: {
          baseURL: process.env.API_URL,
        },
      },

to

  axios: {
    baseURL: process.env.API_URL,
  },

Solution

  • You're using Nuxt's Axios module in the project. There's no need to import Axios for using it. By importing it, you're using a new instance, not the one you've actually injected with baseURL.

    Just replace await axios.get with await this.$axios.get and remove your import.

    <script>
    export default {
      name: 'App',
      data() {
        return {
          categories: [],
          error: null,
        }
      },
      async mounted() {
        try {
          const response = await this.$axios.get('categories')
          this.categories = response.data
        } catch (error) {
          this.error = error
        }
      },
    }
    </script>