Reputation: 751
This seems like a simple Nuxt question, but I just can't figure it out.
When running "NPM run dev" I want to set the Axios baseURL to "localhost/api" and when running from the dist folder after "NPM run generate" I want the baseURL to be "/api".
Is there a simple solution?
Upvotes: 10
Views: 26565
Reputation: 1353
https://nuxt.com/docs/api/nuxt-config#baseurl
NUXT_APP_BASE_URL=/api node .output/server/index.mjs
Upvotes: 0
Reputation: 486
In Nuxt 3 we can use a .env
file. Here's the doc.
# .env
API_URL=http://localhost:8080/api
// nuxt.config
export default defineNuxtConfig({
runtimeConfig: {
// Private keys are only available on the server
apiSecret: '123',
// Public keys that are exposed to the client
public: {
apiUrl: process.env.API_URL
}
}
})
// MyComponent.vue
<script setup>
const config = useRuntimeConfig()
console.log(config.public.apiUrl)
</script>
Upvotes: 1
Reputation: 653
This is the way to do it through the nuxt.config.js
:
let development = process.env.NODE_ENV !== 'production'
module.exports = {
axios: {
baseURL: development ? 'http://localhost:3001/api' : 'https://domain/api'
},
modules: [
'@nuxtjs/axios'
],
}
As you can see, you should specify full URL of your backend, including domain (except SPA-only mode).
And don't forget to install @nuxtjs/axios as dependency to try the example.
Upvotes: 21
Reputation: 5173
you can also set api from outside (eg package.json scripts) by env variable
my package.json fragment (there is additional complexity when browser uses different api url then server side rendering, still all is supported by Nuxt itself with variables API_URL_BROWSER and API_URL)
"scripts": {
"dev-prodapi": "API_URL=https://kairly.com/api nuxt",
"dev": "API_URL=http://localhost:8000/api nuxt",
"dev-spa-prodapi": "API_URL=https://kairly.com/api nuxt --spa",
"dev-spa": "API_URL=http://localhost:8000/api nuxt --spa",
"build": "API_URL_BROWSER=https://kairly.com/api API_URL=https://internal-apihost/api/ nuxt build --modern=server",
"start": "API_URL_BROWSER=https://kairly.com/api API_URL=https://internal-apihost/api/ nuxt start --modern=server",
and using no axios section in nuxt config at all.
Upvotes: 4