In src("@nuxtjs/axios": "^5.3.1",), options use <%= =%> inject into the code:
baseURL : process.browser
? '<%= options.browserBaseURL %>'
: (process.env._AXIOS_BASE_URL_ || '<%= options.baseURL %>'),
it will generate:
baseURL : process.browser
? 'http://localhost:3000/'
: (process.env._AXIOS_BASE_URL_ || 'http://localhost:3000/'),
Now I change env API_URL_BROWSER, but browserBaseURL will not change.
I must rebuild to fix it.
browserBaseURL can change depend on API_URL_BROWSER without rebuild
browserBaseURL not change
(In continuation to #157)
Unfortunately, the thing that is happening is something expected because this is how webpack works! It statically replaces all process.env.* values with their constant value during build. So we can't change it at runtime by an env variable. However, this is possible on server side because of Node.js runtime.
There are some possible workarounds for this problem:
process.env.API_URL_BROWSER in the nuxt state (window.__NUXT__) and restore it at runtime. This only works for SSR mode, not SPA.$axios.setBaseURL(url, [browse_url]) helper which is able to dynamically change base URL. (Prefered)baseURL option to accept a function so that we can write a custom function for baseURL at runtime.emmm...alrignt...
And can you fix this bug?
@jimliang Hmm we can try to implement any of the workarounds I've mentioned above :)
This is quite a problem as it renders it quite unusable in a Docker environment, I don't want to start a build each time a container starts.
For the moment I have to put API_URL_BROWSER in the intermediate docker build which renders my Docker image stuck to a unique URL, bye bye deploying it to a staging or prod server from the same image.
Nevermind, setting ENV API_URL_BROWSER=/ solves my problem
How did you use axios? I have tried this without problems:
async asyncData({ app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
return { ip }
}
From axios module's usage
Just remember: app.$axios (Nuxt module), not axios (normal package) 馃槤!
@pi0 I have a related question: Is it possible to change the proxy url at runtime similar to API_URL?
@lhermann Unfortunately technically no because as it is hardcoded in .js files after the webpack build. But you can use a nuxt plugin to change it according to your needs on runtime: (You may leverage process.client to distinguish it for server and client)
export default function ({ $axios }) {
$axios.defaults.baseURL = 'new baseURL'
}
@pi0 thank you! I actually thought about doing it this way, but I didn't find a good way to let the client know exactly which url to use.
In the end I did this in nuxt.config.js, and it does use the environment variable at runtime 馃憤
proxy: {
"/api/": { target: process.env.API_URL }
}
Proxy is always better idea indeed :)
Most helpful comment
Nevermind, setting
ENV API_URL_BROWSER=/solves my problem