Search code examples
javascriptvue.jsaxiosnuxt.js

Nuxt.Js axios not using baseURL despite it being set correctly


I want to call an API in asyncData()

  async asyncData({ $axios, params, store }) {
    let itemUUID = params.item;
    let item = await $axios.get("/item/" + itemUUID);
    return {item};
  }

Problem: Axios is still making the request on http://localhost:3000 if I do a console.log($axios.defaults.baseURL) the correct baseURL of my API is printed. This also works if I use my store action & make the call by using this.$axios

I am using @nuxtjs/axios 5.13.1 with Nuxt 2.15.6 in SSR mode and configured it with the correct baseURL in the nuxt.config.js

Interestingly, if I edit my page content and a hot module reload is triggered, the correct URL is used. Maybe the question should be if Axios is triggered in the right time, on the server?

Edit: I checked the request that was made on HMR and this was triggered in the client.js. If I call my store inside the created() hook the request gets executed successfully.

My nuxt.config.js:

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

  privateRuntimeConfig: {
    axios: {
      baseURL: process.env.EXPRESS_SERVER_URL,
    }
  },

Solution

  • TLDR; This was not related at all - I forgot to set the auth token for my backend. At the time of axios init it's not present. $axios object doesn't have auth - backend fails.

    On page load the nuxt function nuxtServerInit() is used to get the auth token out of the acces_token cookie.

    I am using a plugin to initialize Axios - with the token from the store. But of couse the token is not present at the time axios is initialized as nuxtServerInit is called after plugin init.

    In my axios.js plugin I changed:

    export default function({ app, error: nuxtError, store }) {
      const token = const token = store.state.user.token;
    
      app.$axios.setToken(token, "Bearer");
    }
    

    to;

    export default function({ app, error: nuxtError, store }) {
      const token = app.$cookies.get("access_token");
    
      app.$axios.setToken(token, "Bearer");
    }
    

    Now the token is present & used for every request happening server-side.