In Vue.js, you can use environment variables for storing sensitive data or configuration settings that may change between deployments.

To use environment variables in Vue.js, follow these steps:

1. Create .env file in your project at root level
2. An env file simply contains key=value pairs of environment variables:

VUE_APP_NOT_SECRET_CODE=some_value

Prefixing your variables with VUE_APP_ is necessary to make them available within your Vue.js application.

Now you can access env variables in your application code:

console.log(process.env.VUE_APP_NOT_SECRET_CODE)

Example:

<template>
  <div>
    <p>API Base URL: {{ apiBaseUrl }}</p>
    <p>API Key: {{ apiKey }}</p>
  </div>
</template>


<script>
export default {
  data() {
    return {
      apiBaseUrl: process.env.VUE_APP_API_BASE_URL,
      apiKey: process.env.VUE_APP_API_KEY,
    };
  },
};
</script>

Note: Remember to keep your .env files in the root of your project and exclude them from version control (e.g., using .gitignore) to avoid accidentally exposing sensitive information.

You can have computed env vars in your vue.config.js file. They still need to be prefixed with VUE_APP_. This is useful for version info

process.env.VUE_APP_VERSION = require('./package.json').version


module.exports = {
// config
}

For More info visit: cli.vuejs.org

Support On Demand!

Vue