Where to keep ENV configuration

Hello, I am using axios in my application.
I need to pass a base URL for the API, and this is different from dev and production.
I thought of using “process.env.API_BASE_URL” and set it as an environment variable. Do you think this is a good approach or should I have a configuration file somewhere and read from that?

1 Like

That’s actually a common approach, yes.

You can take a look at the config directory of vue-cli’s webpack template to see how it’s solved there

1 Like

Thanks, do you think a util/http.js file like looks ok like this?

import axios from 'axios'

// move endpoint to conf, headers
export default axios.create({
  baseURL: process.env.API_BASE_URL
  // headers: {
  //   'Content-Type': 'application/vnd.api+json',
  //   Authorization: 'Bearer {token}'
  // }


Usually you will quickly find that you may want to wrap this base instance further e.g. getUsers, but that’s a good starting point.

I see however that when I do

cross-env API_BASE_URL=http://localhost:3001/ npm start

The env variable is not passed anywhere. Am I doing it wrong? If I log it to the console I just get undefined.

Well, webpack doesn’t inject each and every environmental variable into your app automatically, you have to use the DefinePlugin.

However, our webpack template has that prepared for you. That’s what I was referring to when I wrote earlier:

There you will find two files: dev.env.js and prod.env.js. In those files you can define stuff to inject into your app via the DefinePlugin (any kind of values, doesn’t have to come from your systems ENV):

// /config/dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
  API_BASE_URL: "'http://localhost:3001/'", // hardcoded value, or:
  API_BASE_URL: JSON.stringify(process.env.API_BASE_URL), // dynamically read from the node process' ENV

The latter will read the env variable that you defined when running the build/dev-server and stringify it.

Our webpack config will then use that object and inject those values into our app so you can access process.env.API_BASE_URL in you code.

relevant webpack config:

1 Like

Awesome, thank you!