nuxt-community / axios-module

Secure and easy axios integration for Nuxt 2
https://axios.nuxtjs.org
MIT License
1.19k stars 245 forks source link

Confused about the different ways to set up base URLs #522

Open DaDoBaag opened 3 years ago

DaDoBaag commented 3 years ago

While reading the docs and various tutorials I've seen different ways to set up base URLs for this module and I don't know which I should use. I'm also not sure what the difference between baseURL and browserBaseURL is. I've listed my specific questions below the code examples.

These are the 3 ways I've seen:

  1. via nuxt.config.js axios property

    axios: {
    // either like this
    baseURL: process.env.API_BASE_URL || "http://localhost:3000/api",
    browserBaseURL: process.env.API_BROWSER_BASE_URL || "http://localhost:3000/api",
    
    // or like this
    host: process.env.API_HOST || "localhost",
    port: process.env.API_PORT || 3000,
    prefix: process.env.API_PREFIX || "/api"
    }
  2. via nuxt.config.js axios + RuntimeConfig properties

    
    axios: {
    // only used as default fallback values if no environment variables provided
    baseURL: "http://localhost:3000/api",
    browserBaseURL: "http://localhost:3000/api"
    },

publicRuntimeConfig: { axios: { browserBaseURL: process.env.API_BROWSER_BASE_URL } },

privateRuntimeConfig: { axios: { baseURL: process.env.API_BASE_URL } }


3. automatically via dotenv file (no nuxt config)
```env
// either like this
API_URL=http://localhost:3000/api
API_URL_BROWSER=http://localhost:3000/api

// or like this
API_HOST=localhost
API_PORT=3000
API_PREFIX=/api

My questions are:

  1. What are the differences between these ways and which is the preferred way? If I set both RuntimeConfig and automatic dotenv values which one gets overridden?
  2. What is the difference between baseURL and browserBaseURL and in what tangible use case would I need this separation?
  3. When I want to query a public API with a private API key, how would I store that key so it doesn't get exposed to the client but can still be used when making dynamic requests in SSR mode? I already have a serverMiddleware set up but don't know how to safely use the key there.