Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt How to set baseURL in dev or production

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?

like image 823
SteveO Avatar asked Feb 19 '19 16:02

SteveO


2 Answers

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.

like image 75
DreaMinder Avatar answered Sep 30 '22 14:09

DreaMinder


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.

like image 29
farincz Avatar answered Sep 30 '22 14:09

farincz