Application environment variables undefined when application is served by Amplify

Viewed 448

I have a Vue.js app hosted by AWS Amplify.

In Vue, env vars can be set application-wide by using .env. files. I currently use such files for development and for production modes, containing different values. When locally building and serving my application the above works as expected. However, once Amplify deploys my app (in my case I use Amplify's CD feature), these variables are not defined.

I know I can define the same env vars in Amplify, but that would mean I need to manage these values in two places since won't be redeploying while developing. so this seems to be prone to errors (I will need to remember to update the vars on both the application end and amplify console whenever I need to make a change for example).

I wonder if this behavior is expected or is there something I am missing in my setup.

Thanks!

1 Answers

I was also facing the same issue in my React app.
The thing is, you need to have a .env file in your app with all the environment variables.

Why? — The reason behind that is, it generates static HTML, CSS and JS files. Those files can't access process during the runtime.

After adding all the environment variables in Amplify, you have to add one more command in your build stage in App build specification.

You can refer to this official documentation on how to implement this.


If you don't care much about your environment variables, you can use this hack: printenv. This will store all the environment variables of your OS and your application in the .env file.

My config looks something like this:

build:
      commands:
        - 'printenv >> .env'
        - 'npm run build'
Related