Home / Blog / How to Use Environment Variables in Vite.js
How to Use Environment Variables in Vite.js

How to Use Environment Variables in Vite.js

Mostafa Said
Mostafa Said
Updated: July 30th 2024

Environment variables play a crucial role in modern web development, especially when working with tools like Vite.js and frameworks such as Vue.js. In this comprehensive guide, we'll explore the benefits and mechanics of using environment variables in Vite.js. We’ll also provide valuable insights and practical examples to help you get the most out of this powerful feature.

What is Vite.js?

Vite logo with other frameworks

Vite.js is a cutting-edge build tool designed for speed and efficiency. Unlike traditional bundlers, Vite leverages native ES modules to deliver instant module loading and rapid hot module replacement (HMR). This results in a much faster development experience with quick startup times and near-instant updates.

Vite works smoothly with frameworks like Vue.js, streamlining the development process and enhancing productivity. It simplifies configuration, optimizes performance, and helps you build modern web applications faster and more efficiently.

For a deeper dive into Vite.js and to continue advancing your skills, check out the "Rapid Development with Vite" course on Vue School. This course offers valuable insights and hands-on experience with Vite.js, helping you harness its full potential in your projects.

Now that you're familiar with Vite, let’s quickly dive into what environment variables are and why they're essential.

What are Environment Variables?

Imagine you're building a dynamic, interactive web application. You've carefully crafted your Vue.js components, set up Vite.js for an ultra-fast development experience, and you're ready to roll. However, your app needs to communicate with various services, and you have sensitive data like API keys, database URLs, and configuration settings scattered throughout your code. How do you keep this crucial information secure and manageable without compromising your codebase?

Here is when environment variables are needed. At their core, environment variables are key-value pairs used to configure settings outside of your application code. They allow you to define variables outside of the project’s scope and reference them in your code. So, instead of hard-coding the values directly in your codebase like this:

import { createClient } from '@supabase/supabase-js'

export const supabase = createClient(
  "https://the-real-project-url.supabase.co",
  "the-real-project-key"
)

You can hide the values under environment variables and reference them like this:

import { createClient } from '@supabase/supabase-js'

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_KEY
)

Environment variables helps in adding a layer of security and flexibility by avoiding hard-coding sensitive data in the codebase. This separation of configuration from code helps in keeping sensitive information, like API keys and database URLs, secure. In addition, we can effortlessly switch between development, testing, and production environments without breaking a sweat.

For a deeper dive into Vite.js and to continue advancing your skills, check out the "Rapid Development with Vite" course on Vue School. This course offers valuable insights and hands-on experience with Vite.js, helping you harness its full potential in your projects.

Why Use Environment Variables?

There are many reason why environment variables are important. Let’s go through some of them.

  • Security: By storing sensitive information in environment variables, we reduce the risk of exposing them in the codebase. This is especially important for API keys, database credentials, and other confidential data. In addtion, when using Vite’s server-side environment variables, we eliminate the risk of exposing sensitive data to the browser.
  • Flexibility: Environment variables allow us to manage different configurations for different environments (development, staging, production). This makes it easier to switch between settings without altering the code.
  • Maintainability: Keeping configuration settings separate from the code simplifies code management. It makes the application easier to maintain and reduces the risk of accidentally exposing sensitive information.

Setting Up Environment Variables in Vite.js

Vite.js provides a straightforward way to define and use environment variables. Let's walk through the steps to set up and use environment variables in a Vite.js project with a Vue.js template.

Step 1: Create a Vite.js Project

First, create a new Vite.js project using the Vue.js template. This will set up a Vue project with Vite as the build tool.

# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
npm install
npm run dev

Step 2: Define Environment Variables

Vite.js supports .env files for defining environment variables. Create a file named .env in the root directory of the project. We can define the variables in this file:

VITE_API_URL=https://api.example.com
VITE_API_KEY=your_api_key
DB_PASSWORD=your_db_password

Step 3: Access Environment Variables On the Client-Side

Vite.js exposes environment variables prefixed with VITE_ to the application’s client-side code and the browser. We can access these variables using import.meta.env.

Here's an example of how to use environment variables in a Vue.js component with the <script setup> syntax:

<template>
  <div>
    <h1>API URL: {{ apiUrl }}</h1>
    <h1>API Key: {{ apiKey }}</h1>
  </div>
</template>

<script setup>
const apiUrl = import.meta.env.VITE_API_URL
const apiKey = import.meta.env.VITE_API_KEY
</script>

By using import.meta.env.VITE_API_URL and import.meta.env.VITE_API_KEY, we can reference the environment variables in Vue.js components.

This method helps in avoiding hardcoding values in the codebase, but it does have security limitations. Since all variables prefixed with VITE_ are exposed to the browser, they can be easily accessed by malicious users. To address this, Vite offers a more secure way to define environment variables.

Understanding the VITE_ Prefix

To prevent accidentally leaking environment variables to the client, only variables prefixed with VITE_ are exposed to the Vite-processed code. This means that variables without this prefix are only available on the server side.

For example, consider the following .env file:

VITE_API_URL=https://api.example.com
VITE_API_KEY=your_api_key
DB_PASSWORD=your_db_password

In the client-side code, we can access VITE_API_URL and VITE_API_KEY but not DB_PASSWORD:

console.log(import.meta.env.VITE_API_URL); // "https://api.example.com"
console.log(import.meta.env.VITE_API_KEY); // "your_api_key"
console.log(import.meta.env.DB_PASSWORD);  // undefined

This distinction helps manage which variables should be accessible on the client side and which should remain hidden on the server.

Working with Environment Variables in Multiple Environments

One of the key benefits of using environment variables is the ability to manage different configurations for different environments. Vite.js uses dotenv to make this process simple and efficient.

Step 1: Create Environment-Specific Files

To define Vite environment-specific variables, you can create additional .env files with suffixes that correspond to different environments. For example:

  • .env (default)
  • .env.development (development environment)
  • .env.production (production environment)

Step 2: Define Variables in Each File

Define your environment-specific variables in each file. For example, in .env.development:

VITE_API_URL=https://dev-api.example.com
VITE_API_KEY=dev_api_key

And in .env.production:

VITE_API_URL=https://api.example.com
VITE_API_KEY=prod_api_key

Step 3: Access Environment Variables

Vite.js will automatically load the appropriate .env file based on the current environment. You can access the variables in your code just as before. When running the app in development mode, Vite.js will use the variables from .env.development, and in production mode, it will use the variables from .env.production.

Use-Cases of Environment Variables

Environment variables are versatile and can be used in various scenarios. They might be employed to conditionally enable or disable features, or to configure different settings based on the environment.

Conditional Logic Based on Environment Variables

You can use environment variables to implement conditional logic in your application. For example, you might want to enable or disable certain features based on the current environment.

<template>
  <div>
    <h1>Welcome to Our App</h1>
    <div v-if="isFeatureEnabled">
      <p>This feature is enabled!</p>
    </div>
  </div>
</template>

<script setup>
const isFeatureEnabled = import.meta.env.VITE_FEATURE_FLAG === 'true'
</script>

In your .env file, you can define the feature flag:

VITE_FEATURE_FLAG=true

Using Environment Variables in Build Scripts

You can also use environment variables in your build scripts to customize the build process. For example, you might want to include different sets of dependencies or configurations based on the environment.

"scripts": {
  "dev": "VITE_API_URL=https://dev-api.example.com vite",
  "build": "VITE_API_URL=https://api.example.com vite build"
}

In this example, the VITE_API_URL variable is set differently for development and production builds.

Using Environment Variables in Production

When deploying a Vite.js application to production, managing environment variables becomes crucial for ensuring that the app runs smoothly and securely. Unlike development, where environment variables are typically stored in a .env file, production environments often require a different approach to provide and manage these variables. Here’s how you can handle environment variables in production:

1. Setting Environment Variables in the Deployment Environment

In a production environment, you generally set environment variables directly on the server or hosting platform where your application is deployed. Most modern deployment platforms offer ways to define environment variables through their configuration interfaces or CLI tools. Follow the hosting platform specific instructions to add the environment variables.

2. Using Environment Variables in Build Time

For static site deployments, Vite.js will include the environment variables in the build process. This means that when you run the build command (vite build), Vite will use the environment variables defined in your .env.production file (or environment-specific file) and embed them into the built files. Or, you can directly set the environment variables in the build script:

"scripts": {
  "build": "VITE_API_URL=https://api.example.com vite build"
}

3. Using Environment Variables with Build Tools

If you’re using a build tool or a CI/CD pipeline, ensure that environment variables are correctly passed to the build process. For example, if you're using GitHub Actions, you can define secrets in your repository settings and use them in your workflow files:

- name: Build
  run: npm run build
  env:
    VITE_API_URL: ${{ secrets.VITE_API_URL }}
    VITE_API_KEY: ${{ secrets.VITE_API_KEY }}

4. Verifying Environment Variables in Production

After deploying your application, it's important to verify that the environment variables are correctly set and functioning as expected. You can:

  • Check Logs: Look at server or build logs to confirm that environment variables are being read correctly.
  • Inspect Network Requests: Use browser developer tools to inspect network requests and ensure that the correct environment variables are in use.
  • Implement a Configuration Check: Include a configuration check in your app that runs on startup to validate the presence and correctness of critical environment variables.

Common Pitfalls and Best Practices

When working with environment variables, it's essential to be aware of common pitfalls and adhere to best practices to ensure both functionality and security. Understanding these potential issues and implementing recommended strategies can help you avoid mistakes that could lead to bugs or expose sensitive information.

In this section, we'll explore frequent challenges developers face with environment variables and provide actionable advice on how to manage them effectively.

Prefix Public Variables with VITE_

Vite.js only exposes environment variables that are prefixed with VITE_ to the browser.

Avoid Storing Sensitive Data in Client-Side Variables

While environment variables can help manage configuration settings, avoid storing sensitive data like API keys directly in client-side variables. Make sure to avoid prefixing sensitive data with VITE_ to avoid having security issues.

Use Environment Variables for Configurations Only

Environment variables should be used for configuration settings, not for storing application logic or state. Keep them simple and focused on configuration.

Keep .env Files Out of Version Control

It's a best practice to keep your .env files out of version control to prevent sensitive information from being exposed. You can do this by adding .env to your .gitignore file:

# .gitignore
.env

Document Your Environment Variables

Make sure to document the required environment variables for your project. This can be done in a README.md file or a separate .env.example file that lists all necessary variables without the sensitive values:

# .env.example
VITE_API_URL=https://api.example.com
VITE_API_KEY=your_api_key

# For sensitive data like passwords, we can leave a comment to guide the developer. For example:
# Copy the password from the dashboard to run the app locally -> [url]
DB_PASSWORD=

Conclusion

In this article, we’ve explored the essentials of environment variables in Vite.js, covering their benefits, setup, and advanced usage. From configuring your app for various environments to understanding the security implications, you now have the tools to enhance your application’s flexibility and maintainability.

Related Courses

Start learning Vue.js for free

Mostafa Said
Mostafa Said
With over 7 years of e-learning expertise honed at major companies like Vodafone Intelligent Solutions (_VOIS), Mostafa is full-time instructor at Vue School and a full-stack developer in the wild. He built and maintained dozens of apps using Vue, Nuxt, Laravel, Tailwind, and more. He merges modern teaching methods with coding education to empower aspiring developers of all experience levels. When he's not glued to the code editor, hackathons fuel his competitive spirit, with Deepgram and Appwrite grand prizes under his belt.

Comments

Latest Vue School Articles

Generating Fake Data with Faker.js

Generating Fake Data with Faker.js

Discover the power of Faker.js, the essential JavaScript library for generating realistic fake data, in our new video course created in collaboration with the developers at Vehikl (vehikl.com).
Felipe Flor
Felipe Flor
Database Seeds with the Nuxt Task Runner

Database Seeds with the Nuxt Task Runner

Learn how to integrate Drizzle ORM with Nuxt for type-safe database operations, including database migrations and seeding with Faker.js and Nitro tasks.
Daniel Kelly
Daniel Kelly

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.