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:
Prerequisites
- Basic understanding of JavaScript and Node.js.
- Some knowledge of Vite would be beneficial.
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
.env
files to your repository. Add .env
to your .gitignore
file.VITE_
is recommended).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.
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.
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.