Custom Environment Variables in Vite JS Tutorial 🎯

beginner
15 min

Custom Environment Variables in Vite JS Tutorial 🎯

Welcome to our deep dive into custom environment variables in Vite JS! This lesson is perfect for both beginners and intermediates looking to explore and master this essential concept. Let's get started!

What are Environment Variables? 📝

Environment variables are simple key-value pairs that store configuration data for your application. They help you manage application settings and make your code more flexible and reusable.

Why Use Custom Environment Variables in Vite JS? ✅

  • Secure Configuration: Keep sensitive data like API keys and database credentials hidden from your project code.
  • Easier Deployment: Different environments (e.g., development, staging, production) require different settings. Environment variables make it simple to manage these differences.

Setting Up Custom Environment Variables in Vite JS 💡

Step 1: Install dotenv Package

First, you need to install the dotenv package, which allows you to load environment variables from a .env file.

bash
npm install dotenv

Step 2: Create a .env File

Create a .env file in the root directory of your project. Add your environment variables like this:

VITE_API_KEY=my_api_key VITE_DB_USERNAME=my_username VITE_DB_PASSWORD=my_password

Step 3: Access Environment Variables

To access the environment variables in your Vite JS project, import the dotenv package and call dotenv.config() at the top of your main JavaScript file:

javascript
import dotenv from 'dotenv'; dotenv.config();

Now, you can access the variables using the process.env object:

javascript
console.log(process.env.VITE_API_KEY); // my_api_key

Practical Example 🎯

Let's build a simple weather app that fetches data from an API using a custom environment variable for the API key.

javascript
import axios from 'axios'; import dotenv from 'dotenv'; dotenv.config(); // Fetch weather data using the API key from the .env file async function getWeatherData() { const apiKey = process.env.VITE_API_KEY; const response = await axios.get( `http://api.openweathermap.org/data/2.5/weather?q=London&appid=${apiKey}` ); // Do something with the weather data... } getWeatherData();

Quiz Time 📝

Quick Quiz
Question 1 of 1

What is the purpose of using environment variables in Vite JS?

That's all for now! With this lesson, you're well-equipped to start using custom environment variables in your Vite JS projects. Happy coding! 😊