Vue webpack environment variables configuration - vue.js

I am new to vue in general and i am trying to configure some environment variables for some projects of mine so i can do some tests with cookies but apperently i ran the simple webpack configurations when creating these projects, therefore i dont have access to the config directory to edit said variables.
I created a vue.config.js file and used the following lines:
module.exports = {
publicPath: 'myAppName'
}
However if i run it on development mode, or simply use npm run serve my app runs at "http://localhost:8080/myAppName" instead of simply "myAppName".
How do i correctly configure my environment variables for my projects without having to start over from scratch? I am using vueCli 3 btw.
I tried following these examples but none have worked:
Using Environment Variables with Vue.js
I also have .env file and a .env.development file but i am not sure what to add to it.

Related

How can I use environment variables if I use vuejs with CDN?

I was using Vuejs CDN to develop my app. Now, I want to separate dev and prod since the API endpoints are separated. I don't want to expose my dev API endpoint. How can I do it with the simplest way?
I tried to use dotenv. Put the DEBUG variable in .env.
var debug = process.env.DEBUG;
console.log(debug);
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
var vm = new Vue({...
My .env file
DEBUG=true
I can read the debug variable. However, it gives an error of "Vue is not defined" since I didn't install Vue with npm. Or I must install Vue with npm?
If you're using Vue CLI, facilities for this are already built in in the form of .env files. You'd create .env.dev and .env.production files (and probably a .env.local for local development), containing:
VUE_APP_ENDPOINT=https://...
Which in your Javascript files you can access as:
const endpoint = process.env.VUE_APP_ENDPOINT;
Then you create different builds for your two different environments:
vue-cli-service build --mode dev # or --mode production
The variables will be baked into the build, so your two different builds only contain their respective endpoints.

How to access react-native-config ENV variables in babel.config.js?

I'm using react-native-config for setting environment variables in my react-native app. Now I want to use the ENV environment variable in the babel.config.js file to apply a plugin only when running the app in production. Basically what I want to do is apply a babel plugin only when running in production. Is this the correct way to achieve my goal?
How can I use the variable in the babel.config.js file? I tried importing Config from the react-native-config package and tried to access the variable via Config.ENV but that doesn't seem to work.

Missing .env in Vue CLI after run build

I'm building an app using Vue CLI 3.
I've included .env in my project and everything works fine.
But when i'm building the app for production via npm run build there is no .env file in my dist folder, so i can't change my environmental variables in production server.
Any solution or it's just fine?
This is supposed to happen. The env variables are embedded in your build.
You can make seperate .env files for production. These variables will be used during the production build.
Create a new .env file named: .env.production
Source: https://cli.vuejs.org/guide/mode-and-env.html#modes
It is normal because application needed to be recompiled when .env file changed.
For convenience you can use .env.prod or .env.dev for your CI/CD pipeline.

Provide enviroment variables for production vue build

I would like to achieve following:
a Vue application is build with npm build,
then the /dist result is copied to some environment
in this enviroment I have some static setting file with name=value settings
the Vue application should read this setting from local folder where it is running or default to some setting
What is the best way to do this.
If you want "to inject" some settings to the bundled app so I think it can be possible only with another js file (globalConfig.js) with global object like:
window.myAppSettings = {
MY_VARIABLE: 'some_value'
}
Which will be copied somehow to your dist folder on a particular environment.
You should also prepare your app to reference that file:
Firstly, add this settings object as external lib in vue.config.js
module.exports = {
chainWebpack: config => {
config.externals({
'my-app-settings': 'myAppSettings'
})
}
}
So you can get your settings in code:
import mySettingsObject from 'my-app-settings'
//...
let myValue = mySettingsObject.MY_VARIABLE
Add reference to globalConfig.js in index.html file in the head section:
<script src="<%= BASE_URL %>globalConfig.js"></script>
Local Development
Probably you will need some default settings to be able to debug your app locally. In this case you can create localConfig.js in your public folder with some default values.
Then change your script in index.html to this:
<script src="<%= BASE_URL %><%= VUE_APP_GLOBAL_SETTINGS_VERSION %>Settings.js"></script>
Then create two files in the project root .env.local and .env.production:
// .env.local
VUE_APP_GLOBAL_SETTINGS_VERSION=local
and
// .env.production
VUE_APP_GLOBAL_SETTINGS_VERSION=global
So when you run npm run serve it will load your local config and your app will load localSettings.js.
And when it builds with npm run build it will load globalSettings.js because building uses a production mode by default.
If you created your project using Vue CLI 3 you can do like this.
Make sure your settings file is named .env and place it in your project root.
In the .env file, your variables should be prefixed with "VUE_APP_"
VUE_APP_SOMEKEY=SOME_KEY_VALUE.
Access them with process.env.*.
console.log(process.env.VUE_APP_SOMEKEY) // SOME_KEY_VALUE
Here's some more info on evironment variables in vue: Vue CLI 3 - Environment Variables and Modes
EDIT:
Sorry. I probably misunderstood your question. This solution will not work if your settings file is in the dist folder.

Vue-cli 3 Environment Variables all undefined

I've tried all of the solutions out there but none seem to work for me. I just want to store some values in a .env file within my Vue app but simply trying to log process.env returns an empty object from within the component.
My .env file
VUE_APP_URL={api url}
VUE_APP_TOKEN={token}
My plan was to set these environment variables to data properties but it always returns undefined. If I do console.log(process.env.NODE_ENV) from webpack.config.js it will show that I'm in development but if I tried doing the same from within the component like
mounted() {
this.$nextTick(() => {
console.log(process.env.VUE_APP_URL);
})
}
It just returns undefined.
A few tips for people who land here:
Make sure your .env files are in the project root folder (and not in say src/)
Variable names should start with VUE_APP_ if to be statically embedded into the client bundle
Restart the dev server or build your project for changes to take effect
If you are migrating from a webpack based solution make sure that you replace : (from JSON config) with = (dotenv format). Easy to miss
Make sure you've saved any changes to your .env files.
In old Vue versions environment variables were defined in e.g. config/dev.env.js instead of the .env files in root
I figured it out - I had to install dotenv-webpack and initialize it in webpack.config.js which is odd because none of the docs stated that I needed to do so.
Install dotenv-webpack and configure the vue.config.js file as follows.
npm install dotenv-webpack --save-dev
Add this to your config file:
const Dotenv = require('dotenv-webpack');
module.exports = {
configureWebpack: {
plugins: [
new Dotenv()
]
}
}
In your .env file make sure you add VUE_APP_ before your variables like this:
VUE_APP_VAR1=example
VUE_APP_VAR2=value
Now you can access these variables in your Vue application:
console.log(process.env.VUE_APP_VAR1); // "example"
console.log(process.env.VUE_APP_VAR2); // "value"
Here some links for reference:
https://www.npmjs.com/package/dotenv-webpack
https://cli.vuejs.org/guide/webpack.html
https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
so I use
VUE_APP_API_URL (this doesn't work)
then I change it to
VUE_APP_APIURL (this works)
hope it helps
If your vue-cli version is higher than 3.x and you put your .env files in root directory like said in comments. Than you can access your environmental variables from components (like this process.env.VUE_APP_YOUR_VARIABLE).
As said in vue-cli docs
Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access
them in your application code: console.log(process.env.VUE_APP_SECRET)
I put my .env file in the root directory and appended each variable with VUE_APP_.
To demonstrate this, for example, if the variable you want to use is API_BASE_URL
In your .env file, you put the variable as VUE_APP_API_BASE_URL=baseurl/api/v1
To access it in your files, you do process.env.VUE_APP_API_BASE_URL.
CAVEAT:
Never put any sensitive information you don't want anybody to see, on your front-end. The most common thing you won't want anybody to see (as regards web development) is your API Key. There are real consequences to doing this. This is one such example of someone who has been burned exposing API keys to the public.
However, even if you put your sensitive data in a .env file and add the .env file to a .gitignore file (hence not pushing it to a Git repository hosting service e.g Github, BitBucket, Gitlab etc.), your data is still not safe on the front-end. It's only safe when this is done on back-end code as it will be hosted on a server.
In the front-end, anyone who is determined enough can find your sensitive information. All your information is available on a browser and all that person needs to do is to open the dev tools and check the Sources tab, and BOOM all your sensitive information is laid bare.
Environment variables on the front-end are only useful when you want one reference point for NON-SENSITIVE information, such as a BASE URL, as seen in the example above. A BASE URL can change during the course of development and you won't want to change all references in the application folder manually. It is tedious plus you may miss a few, which would lead to errors.
If you want to avoid exposing your API keys and other sensitive information you may require on the front-end, take a look at this article.
This is what worked for me. I previously created my .env.development and .env.production files in the root folder by manually by right-clicking in the Exploer in VS Code and adding a new file. This kept giving me undefined.
I deleted the files and first installed npm install touch-cli -g
Once installed, i added the environment files as such touch .env.production and touch .env.productionand itworks. So I think there's a difference between how these env files are generated.
NOTE: I do not have webpack installed. Just using the vue cli to build
VS Code ExplorerChrome Developer Tools
IF you are using VITE, use VITE_ in stead of VUE_APP
Vue CLI dotenv usage suffers the inability to provide the .env variables other than prefixed with VUE_APP_. This is OK but this is far not enough to satisfy any even little serious web project that wants to conveniently and securely manage its (sometimes huge) list of variables for different environments.
Here is the solution that makes use of .env variables as convenient as on backends with dotenv.
With this solution you could access your MY_EXTERNAL_API_KEY from your .env[.environment] file in your code like this const key = process.env.MY_EXTERNAL_API_KEY.
It provides:
The convenience of using non-prefixed with VUE_APP_ variables' names and use .env variable expansion feature (use ${VARNAME} kind of variables)
The necessary security: your variables are neither available at browser console with console.log(pocess.env.MYVAR) at run time nor are explorable via text search by their names from .env files within the built application's JS bundle.
You can still use original Vue CLI solution along;
For this use dotenv-webpack plugin in your vue.config.js as follows:
const Dotenv = require('dotenv-webpack');
const envPath = function() {
return (!process.env.NODE_ENV || (process.env.NODE_ENV === 'development')) ?
'./.env' :
`./.env.${process.env.NODE_ENV}`;
}
const dotenvArgs = {
expand: true,
path: envPath()
};
module.exports = {
//... some other config here
configureWebpack: {
plugins: [
new Dotenv(dotenvArgs)
]
}
};
Here:
expand: true allows for ${MYVAR} variables expansion;
path: envPath() allows to define custom .env file name depending on your Vue CLI project environments, and the path depending on you project structure;
There are other useful dotenv-webpack options you could use.
I believe this solution is good enough to fully satisfy most frequent use cases.
NB: Remember as you pass your secret variables set via .env into HTTP requests from your front-end (e.g. an API key in a call to some external API) they are visible to any one who knows where to look. To diminish security risks for this situation there are different solutions.
Just to hint you have either to:
provide only publicly open data via your application;
or authenticate your application (or parts of it) via some authentication service (login/password + JWT|sessions, external authentication providers e.g. Facebook, Google etc.);
or resort to server-generated application.
But this is the whole separate subject.
if you are cominng from VUE-cli-2 or you just cloned/installed an old vuejs project and you can't find .env file, this article explains what you have to do to set your .env variables as they environment files are probably located in config/dev.env.js (Note: this is peculiar to Vue-cli-2 files)
Here is also a solution and a detailed explanation for Vue-cli-3 .env related issue
What worked for me was changing from .env to .env.local. Haven't investigated WHY but I checked an old project and saw that I had a .env.local instead and did same for this project that would not pick the values from .env irrespective of whether vars where prefixed with VUE_APP and it worked.
It seems environment variables are not accessible in child Vue components. Best to declare them globally in main.js with Vue.prototype.env = process.env;
I know that this question was asked about vue-cli 3, which generates code for Vue 2. But it is the top result if you google for "vue3 does not embed env" and similar queries, so I assume that a lot of people end up here when having trouble with process.env variables being undefined in their Vue 3 app.
So this is an answer about how to fix your Vue 3 env issues.
This is what causes the confusion
If you google for env problems with vue, you end up in the vue-cli docs. But vue-cli was replaced by create-vue in Vue 3. There is a alert box at the top of the page that tells you this, but you've probably missed it.
If you did not miss it and followed one of the two links in the box, you ended up in the Vue 3 tooling guide or in the create-vue repo. None of those resources mention env variables. But you learn that create-vue is based on Vite.
If you follow that lead and google for "vite env", you end up in the vite documentation, where you finally find the answer:
env variables have to be prefixed with VITE_ to be compiled into the app (as opposed to VUE_APP_ in vue 2)
env variables will be available in import.meta.env in your app (as opposed to process.env in vue 2)
The latter one is what took me the longest to figure out.
This is how you need to do it
in an .env file in your project root:
VITE_MY_ENV_VAR=foo
The docs will also tell you about the different naming patterns for .env files in Vite. Very useful information if you work with different environments!
in your app:
const my_env_var = import.meta.env.VITE_MY_ENV_VAR
I hope this saves someone the time for figuring this out.
It might also help: make sure your .env files are in lowercase letters because in Linux it won't work even if it is working in windows
The answer provided here helped me out. I'm using Laravel with an odd setup for Vue 2.x. The project is also using Laravel Mix. Here's the solution:
Inside of your .env file, which is a sibling of package.json:
MY_ENVIRONMENT_VARIABLE=my_value
Inside of webpack.mix.js:
const { mix } = require('laravel-mix');
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.EnvironmentPlugin (
['MY_ENVIRONMENT_VARIABLE']
)
]
};
});
Afterwards, an npm run dev or npx mix should allow you to use these variables.
Credit: Thorsten Lünborg