How to configure environment specific parameters with Vue.js and Amplify

Yan Cui
2 min readMar 2, 2021

When you start a new Vue.js project that needs to interface with APIs running in AWS, there’s a good chance you will have these lines of code:

import Amplify from 'aws-amplify'Amplify.configure({
Auth: {
region: 'us-east-1',
userPoolId: 'xxx',
userPoolWebClientId: 'xxx',
mandatorySignIn: true
}
})

These few lines of code let you use the aws-amplify library to authenticate the user against a Cognito User Pool and support common flows such as sign-up, sign-in, sign-out, forgotten passwords and change passwords.

But, as you provide your Vue.js project across the different environments — dev, test, staging and production — these settings have to change.

So instead of hardcoding them, you should inject them via environment variables. And fortunately for us, Vue.js supports the use of .env files out-of-the-box. However, a caveat that stomped me for a few hours today was that these environment variables need to be prefixed with VUE_APP_.

This was mentioned in the docs but unless you knew what you were looking for, it wasn’t obvious.

Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. It is to avoid accidentally exposing a private key on the machine that could have the same name.

So, you change your code to something like this:

import Amplify from 'aws-amplify'Amplify.configure({
Auth: {
region: process.env.VUE_APP_REGION,
userPoolId: process.env.VUE_APP_USER_POOL_ID,
userPoolWebClientId: process.env.VUE_APP_CLIENT_ID,
mandatorySignIn: true
}
})

And assuming you’re using the AWS Amplify service to deploy this Vue.js application, you need to configure these as environment variables in the Amplify console.

And pull them into a .env file during the build process. Again, the environment variables in the .env file needs to be prefixed with VUE_APP_.

So, in the amplify.yml file, add these lines to the build phase, just before the npm run build step.

- echo "VUE_APP_REGION=$REGION" >> .env 
- echo "VUE_APP_USER_POOL_ID=$COGNITO_USER_POOL_ID" >> .env
- echo "VUE_APP_CLIENT_ID=$COGNITO_CLIENT_ID" >> .env

Your amplify.yml will probably look something like this.

version: 1
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- echo "VUE_APP_REGION=$REGION" >> .env
- echo "VUE_APP_USER_POOL_ID=$COGNITO_USER_POOL_ID" >> .env
- echo "VUE_APP_CLIENT_ID=$COGNITO_CLIENT_ID" >> .env
- npm run build
artifacts:
baseDirectory: dist
files:
- '**/*'
cache:
paths:
- node_modules/**/*

Now they’ll be bundled into the app when Amplify builds and deploys it.

Originally published at https://theburningmonk.com on March 2, 2021.

--

--

Yan Cui

AWS Serverless Hero. Follow me to learn practical tips and best practices for AWS and Serverless.