Nuxt How to set baseURL in dev or production
Asked Answered
J

4

10

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?

Japheth answered 19/2, 2019 at 16:24 Comment(0)
M
21

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.

Magnetic answered 19/2, 2019 at 17:59 Comment(3)
Worked perfect!Japheth
@Japheth Cool. In this case you'd better mark this question as resolved, just sayingMagnetic
Not Working BroDefeasible
T
4

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.

Tenpenny answered 23/7, 2019 at 19:39 Comment(0)
E
1

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>
Embellishment answered 30/11, 2022 at 13:56 Comment(0)
S
0

https://nuxt.com/docs/api/nuxt-config#baseurl

NUXT_APP_BASE_URL=/api node .output/server/index.mjs
Snivel answered 16/6, 2024 at 12:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.