9

I want to access my environment variables from the template of vue single file components however, doing the following:

<img :src="`${process.env.VUE_APP_API_BASE_URL}/image/${image.filename}`" alt="" />

gives me the error:

 Property or method "process" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

i know my environment variables are set up correctly as i can use them in other places, and i can use a workaround to create a new variable on the component and reference that:

data() {
  return {
    BaseUrl: process.env.VUE_APP_API_BASE_URL,
  };
},

<img :src="`${BaseUrl}/image/${image.filename}`" alt="" />

and that is able to load the image correctly, but how can i access the env variables directly in the template without the need to initialise a new variable for each component?

4
  • Are you serverside rendering with Nuxt.js? Commented May 9, 2021 at 17:05
  • 1
    that is because process is global, but in template are used local vars (like there is this. before them), so you could define computed prop for example $process: process, so it could be used in template placeholders. Commented May 9, 2021 at 18:03
  • @TJ no this is a spa Commented May 9, 2021 at 21:05
  • @willystyle is there a way to load it into all components automatically? so i don't have to define it individually? Commented May 9, 2021 at 21:06

3 Answers 3

7

process.env environment variables are replaced with actual values at compilation time. The error means that this doesn't happen in templates.

Things can be defined globally for all components, e.g. for Vue 2:

Vue.prototype.$baseUrl = process.env.VUE_APP_API_BASE_URL;

Putting too much code into templates is a bad practice. In this case image URL can be defined as computed, or as method for image provided by v-for.

Sign up to request clarification or add additional context in comments.

Comments

4

For Vue3 in the main.js file you can write:

import { createApp } from 'vue';
const app = createApp(App);
app.config.globalProperties.$myVariable = process.env.VUE_APP_MY_VARIABLE;

And then access in every template:

<template>
  My variable is: {{ $myVariable }}
</tempate>

1 Comment

We cannot access process.env in a client side script. Am I missing something?
1

In Vue 3 + Vite + TypeScript, I did not need to use globalProperties or any other magic. Any environment variables defined in the .env file are directly accessible in the SFC. Just create a ref (or computed) in your script section like this:

const BaseUrl = ref<string>(import.meta.env.VITE_API_BASE_URL)

and then use it in your template section. Remember that the variable name must start with the string VITE_ for this to work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.