Published:

Vue 3 + Vite - Access Environment Variables from dotenv (.env)

This is a quick tutorial on how to create and access environment variables in Vue 3 with a dotenv (.env) file.

Vue 3 apps built with Vite support dotenv environment variables out of the box, so all you need to do is add a .env file to the root folder of your Vue project.


How to make env variables accessible to the Vue client app

There's only one gotcha, to access environment variables from the client app they must be prefixed with VITE_. Otherwise they will only be accessible on the server side.

You can access environment variables (with the VITE_ prefix) from your Vue app via the import.meta.env object. For example const myVar = import.meta.env.VITE_MY_VAR;.


Vue 3 + Vite env variable example on StackBlitz

Here's an example Vue 3 + Vite app that contains a couple of environment variables. It shows that the env variable prefixed with VITE_ is accessible to the App component and the server side only variable is not.

(See on StackBlitz at https://stackblitz.com/edit/vue-3-vite-access-environment-variables-from-dotenv)

 

Example dotenv (.env) file

The dotenv file from the example app. It defines two environment variables, the one prefixed with VITE_ is accessible to the Vue client app, and the one without the prefix is only accessible to server side code.

# variables prefixed with VITE_ are accessible from the vue client app
VITE_MY_ENV_VARIABLE=environemnt variable value from .env file

# variables without the VITE_ prefix are NOT accessible from the vue client app
SERVER_SIDE_ONLY_VAR=this can't be accessed on the client
 

Vue 3 App Component

The App component attempts to display both environment variables, but only has access to the one prefixed with VITE_.

It accesses variables in the .env file with the special object import.meta.env.

<script setup>
const publicEnvVar = import.meta.env.VITE_MY_ENV_VARIABLE;
const privateEnvVar = import.meta.env.SERVER_SIDE_ONLY_VAR;
</script>

<template>
    <div class="card m-3">
        <h5 class="card-header">Vue 3 + Vite - Access Environment Variables from dotenv (.env)</h5>
        <div class="card-body">
            <p>VITE_MY_ENV_VARIABLE: {{publicEnvVar}}</p>
            <p>SERVER_SIDE_ONLY_VAR: {{privateEnvVar}}</p>            
        </div>
    </div>    
</template>
 

For more info on using environment variables in a Vue app built with Vite see https://vitejs.dev/guide/env-and-mode.html.

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some Vue 3 Help?

Search fiverr to find help quickly from experienced Vue 3 developers.



Supported by