Vite JS Tutorial: Working with Environment Variables (`.env`)

beginner
8 min

Vite JS Tutorial: Working with Environment Variables (.env)

Welcome to another exciting tutorial on CodeYourCraft! Today, we're diving into the world of Vite JS, focusing on a crucial topic - managing environment variables using .env files. Let's get started! šŸŽÆ

What are Environment Variables?

Environment variables are global configuration settings that can be accessed across your application. They are essential for managing sensitive data like API keys, database credentials, and other secrets. šŸ’”

Setting up Environment Variables in Vite JS

To work with environment variables in Vite JS, you'll first need to install the dotenv package. You can do this by running:

bash
npm install dotenv

or

bash
yarn add dotenv

Creating a .env file

Next, create a .env file in your project root directory and add your environment variables like so:

VITE_API_KEY=your_api_key DATABASE_URL=your_database_url

Importing and Using Environment Variables

Now, you can import and access your environment variables in your JavaScript files. Here's a simple example:

javascript
// Import dotenv import dotenv from 'dotenv'; dotenv.config(); // Access environment variables const apiKey = process.env.VITE_API_KEY; const dbUrl = process.env.DATABASE_URL; // Use the environment variables console.log('API Key:', apiKey); console.log('Database URL:', dbUrl);

Pro Tip:

šŸ“ Remember to never check .env files into version control systems, as they contain sensitive data. Instead, use .gitignore to exclude the .env file.

Advanced Usage: Multiple .env Files

In some cases, you might have different environment variables for different environments, like development, testing, and production. Vite JS supports this by using different .env files for each environment.

To create a .env file for a specific environment, simply name the file .env.<ENV_NAME>, e.g., .env.test or .env.production. Then, access the appropriate environment variables as usual.

javascript
import dotenv from 'dotenv'; // Determine the environment based on the NODE_ENV variable const envFile = `.env.${process.env.NODE_ENV}`; dotenv.config({ path: envFile }); // Access environment variables const apiKey = process.env.VITE_API_KEY; const dbUrl = process.env.DATABASE_URL; // Use the environment variables console.log('API Key:', apiKey); console.log('Database URL:', dbUrl);

Quiz Time!

Quick Quiz
Question 1 of 1

Which package do you need to install to work with environment variables in Vite JS?

That's it for today's tutorial on environment variables in Vite JS! In the next lesson, we'll explore how to set up routing in your Vite JS applications. Until then, happy coding! šŸ’”šŸš€