1
votes

I am using nuxt.js and trying to show images dynamically. That's why I use BASE_URL variable inside .env file and access image files according to the BASE_URL in my local environment.

.env file

BASE_URL = https://pctool.herokuapp.com
DB_HOST = dummy_host_name
DB_USER = dummy_user_name
DB_NAME = dummy_database_name
PASSWORD = dummy_password

in image.vue file

template

 <img class="pic-0" :src="makeImagePath(product.image[0])"/>

script

methods: {
    makeImagePath (img_name) {
      return process.env.BASE_URL + "/product/" + img_name;
    }
}

Local output is image showing with proper url

But after deploy the code to Heroku is not working with env variable.

heroku env

heroku env veariables

Deployed output is

image is not showing and url is also not proper

But if I make the URL hardcoded like below script

methods: {
    makeImagePath (img_name) {
      return  "https://pctool.herokuapp.com/product/" + img_name;
    }
}

Then it's working both places. Now in that position URL is not dynamic, I have to change the URL from local to production wherever I use that concept in my project. That's why I want to make the URL dynamic so that there was no conflict during deployment.

2

2 Answers

0
votes

Generally you should not commit your .env file. In your Heroku app under settings you can set the environment variables.

enter image description here

There you can define these again:

BASE_URL = https://pctool.herokuapp.com
DB_HOST = dummy_host_name
DB_USER = dummy_user_name
DB_NAME = dummy_database_name
PASSWORD = dummy_password
0
votes

Finally figured it out. If you want to access .env variables client side, you need to define them in the Heroku Config Vars settings, but then you also need to add this inside your nuxt.config.js file, for example:

publicRuntimeConfig: {
    baseUrl: process.env.BASE_URL,
    originHeader: process.env.ORIGIN_HEADER
}

Then you'll be able to access them like this: this.$config.baseUrl

Of course, be sure you do not expose any private variables like API keys or whatever in this way, as these are client-side and therefore public. Cheers!