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

Problem: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 files 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.

Click here for example

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;

    <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>            

For more info on using environment variables in a Vue app built with Vite see

More Vue 3 Posts

More Error Tutorials >>

Vue 3+VeeValidate – Form Validation Example (Composition API)

Vue 3+VeeValidate – Required Checkbox Example (Composition API)

Vue 3+Pinia-JWT Authentication Tutorial & Example

Leave a Reply

Your email address will not be published.

error: Content is protected !!