0
0
Vueframework~5 mins

Environment variables management in Vue

Choose your learning style9 modes available
Introduction

Environment variables help you keep important settings separate from your code. This makes your app easier to change and safer.

You want to store API keys without putting them directly in your code.
You need different settings for development and production versions of your app.
You want to change the app's behavior without changing the code.
You want to keep sensitive information like passwords hidden from public view.
Syntax
Vue
# .env file example
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My Vue App

In Vue, environment variables must start with VITE_ to be accessible in your code.

Use a .env file in your project root to define variables.

Examples
This file is used only when running the app in development mode.
Vue
# .env.development
VITE_API_URL=https://dev.api.example.com
VITE_APP_TITLE=My Vue App (Dev)
This file is used when building the app for production.
Vue
# .env.production
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My Vue App
Access environment variables in your Vue components or scripts using import.meta.env.
Vue
console.log(import.meta.env.VITE_API_URL)
console.log(import.meta.env.VITE_APP_TITLE)
Sample Program

This Vue component shows how to read environment variables and display them in the page.

Vue
<template>
  <div>
    <h1>{{ title }}</h1>
    <p>API URL: {{ apiUrl }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const title = ref(import.meta.env.VITE_APP_TITLE)
const apiUrl = ref(import.meta.env.VITE_API_URL)
</script>
OutputSuccess
Important Notes

Remember to restart your development server after changing environment variables.

Do not commit sensitive keys to public repositories.

Use different .env files for different environments to keep settings organized.

Summary

Environment variables keep important settings outside your code.

Vue requires variables to start with VITE_ to use them.

Access variables in code with import.meta.env.