knot22
knot22

Reputation: 2768

Store environment value in Vue upon app initialization

In a basic web app built using VueJS a call is made to an API that responds with an object containing the environment name. For example:
https://appsdev/mysimpleapp/api/environment
returns
{"applicationName":"My Simple App","version":"1.0.0.0","environment":"DEV"}

Currently, a nav button is set up to conditionally show if the environment is DEV. Here are the pertinent parts of that page:

<template>
   <!-- other content here -->
   <div @click="updateMenu()" v-show="['DEV'].includes(environment)"><router-link :to="{name: 'dev-notes'}">Dev Notes</router-link></div>
</template>

<script>
// other logic here
data() {
    return {
        environment: null
    }
},
created() {
    this.getEnvironment();
},
methods: {
    async getEnvironment() {
        const environmentDetails = await this.$service.access('environment').get();  // uses Axios to access API
            this.environment = environmentDetails.environment;
        }
    }
}
</script>

While this approach works, there is a noticeable delay in the "Dev Notes" nav button appearing while the app hits the API. Plus, every time the page loads, there is a call to the API.

Looking to improve upon this, it seems like it might be better to hit the API once, when the app initializes, store that value in a variable somewhere and then refer to that variable for conditionally showing the "Dev Notes" nav button. Vuex seems like overkill for such a simple thing and this app doesn't have the .env files that this post describes so how can this be achieved?

Upvotes: 2

Views: 303

Answers (1)

Dan
Dan

Reputation: 63129

You can access the environment mode info straight from Vue CLI using node's process.env, which is a feature that's available by default. Specifically, process.env.NODE_ENV tells whether the app is running in production or development or some other mode. From the Vue CLI docs:

For example, NODE_ENV will be set to "production" in production mode, "test" in test mode, and defaults to "development" otherwise.

You can test this anywhere in your project, for example:

if (process.env.NODE_ENV === 'production') {
  console.log('PRODUCTION');
} else if (process.env.NODE_ENV === 'development') {
  console.log('DEVELOPMENT');
} else {
  console.log('OTHER');
}

Upvotes: 2

Related Questions