Vite / Vite Configuration

Using Environment Variables With Vite

In this tutorial, we'll learn how to use environment variables in Vite. Environment variables allow you to inject configuration into your app without changing the source code.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers how to configure Vite for different use cases

Using Environment Variables With Vite

1. Introduction

In this tutorial, we will be learning about how to use environment variables in Vite. Environment variables provide a way to influence the behavior of software on your system. They are especially useful for storing sensitive information such as API keys, database credentials, etc.

By the end of this tutorial, you will learn how to:

  • Define and use environment variables in Vite.
  • Access these variables within your Vite application.

Prerequisites
- Basic understanding of JavaScript and Node.js.
- Some knowledge of Vite would be beneficial.

2. Step-by-Step Guide

Vite loads environment variables from .env files in your project root. It also has support for .env files for different modes.

Creating .env file

In your project root, create a file named .env and add your variables like this:

VITE_APP_TITLE=My Vite App
VITE_API_KEY=1234567890

Accessing Environment Variables

You can access these variables in your JavaScript code like this:

console.log(import.meta.env.VITE_APP_TITLE)
console.log(import.meta.env.VITE_API_KEY)

Best Practices

  1. Do not commit your .env files to your repository. Add .env to your .gitignore file.
  2. Use a prefix for your variables (VITE_ is recommended).

3. Code Examples

Example 1: Setting a Title Using Environment Variables

In .env file:

VITE_APP_TITLE=Welcome to Vite!

In JavaScript:

document.title = import.meta.env.VITE_APP_TITLE;

This will set the title of your webpage to "Welcome to Vite!".

Example 2: Fetching Data Using an API Key from Environment Variables

In .env file:

VITE_API_KEY=1234567890

In JavaScript:

fetch(`https://api.example.com/data?apiKey=${import.meta.env.VITE_API_KEY}`)

This will make a fetch request using the API key from your environment variables.

4. Summary

In this tutorial, we have learned how to use environment variables in Vite, including how to define and access these variables in our Vite application.

Next, try to use environment variables in your Vite projects, and remember the best practices we've discussed.

For more information, you can check out the Vite documentation on environment variables.

5. Practice Exercises

Exercise 1: Create a Vite application and define an environment variable named VITE_USER_NAME. In your main JavaScript file, log this variable to the console.

Solution:

In .env file:

VITE_USER_NAME=John Doe

In JavaScript:

console.log(import.meta.env.VITE_USER_NAME);

Exercise 2: Define an environment variable named VITE_API_URL. Use this variable to make a fetch request and log the response to the console.

Solution:

In .env file:

VITE_API_URL=https://api.example.com/data

In JavaScript:

fetch(import.meta.env.VITE_API_URL)
  .then(response => response.json())
  .then(data => console.log(data));

Remember to replace https://api.example.com/data with a real API URL.

Tips for Further Practice

Keep experimenting with different uses of environment variables. Try using them for different modes (development, production, etc.) and see how they can help you manage your application configuration more effectively.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help