DEV Community

Cover image for How to Use Environment Variables in a React.js App with Vite
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

How to Use Environment Variables in a React.js App with Vite

Environment variables are essential in modern web development. They allow you to store sensitive data, configuration options, and settings outside of your source code. If you’re using React.js with Vite, handling environment variables becomes even more streamlined. In this blog post, we’ll dive deep into how to set up and use environment variables in your React.js app powered by Vite.



Why Use Environment Variables?

Environment variables provide several benefits:

  • Security: Keep sensitive information, like API keys and secrets, out of your source code.
  • Flexibility: Configure your app for different environments (development, production, testing).
  • Maintainability: Avoid hardcoding values, making your app easier to maintain and deploy.

Vite simplifies working with environment variables while adhering to best practices.


Setting Up Environment Variables in Vite

Here’s how you can set up and use environment variables in a React.js app with Vite:

1. Create a Vite React Project

First, create a new React.js project using Vite:

npm create vite@latest my-react-app --template react
cd my-react-app
npm install
Enter fullscreen mode Exit fullscreen mode
2. Define Your Environment Variables

Create a .env file in the root of your project. This file will store your environment variables. For example:

VITE_API_URL=https://api.example.com
VITE_API_KEY=your-api-key
Enter fullscreen mode Exit fullscreen mode

Important: Prefix all variables with VITE_. Vite enforces this convention to differentiate app-specific variables from other system-level variables.

3. Access Environment Variables in Your Code

You can access environment variables in your React.js components or modules using import.meta.env. Here’s an example:

function App() {
  const apiUrl = import.meta.env.VITE_API_URL;
  const apiKey = import.meta.env.VITE_API_KEY;

  console.log('API URL:', apiUrl);
  console.log('API Key:', apiKey);

  return (
    <div>
      <h1>Environment Variables with Vite</h1>
      <p>API URL: {apiUrl}</p>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
4. Add Environment-Specific Files

For different environments, you can create additional .env files:

  • .env.development for development-specific variables.
  • .env.production for production-specific variables.
  • .env.test for testing-specific variables.

Vite will automatically load the appropriate file based on the NODE_ENV value.

For example, in .env.production:

VITE_API_URL=https://api.prod.example.com
Enter fullscreen mode Exit fullscreen mode

To build your app for production:

npm run build
Enter fullscreen mode Exit fullscreen mode
5. Secure Your .env File

Ensure that your .env file is added to your .gitignore to prevent sensitive data from being pushed to version control:

# .gitignore
.env
Enter fullscreen mode Exit fullscreen mode

Best Practices for Using Environment Variables

  1. Prefix Variables: Always prefix variables with VITE_ to ensure compatibility with Vite.
  2. Keep Secrets Out of Client-Side Code: Avoid exposing sensitive data in the frontend. Use server-side code to handle critical operations whenever possible.
  3. Validate Variables: Use a library like dotenv or custom scripts to validate required environment variables.
  4. Document Variables: Maintain a .env.example file to document required variables for your app:
# .env.example
VITE_API_URL=<your-api-url>
VITE_API_KEY=<your-api-key>
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Common Issues

  • Variables Not Available: Ensure your .env file is correctly placed in the root directory and variables are prefixed with VITE_.
  • Values Not Updating: Restart the development server after making changes to the .env file.
  • Exposure of Secrets: Avoid putting sensitive secrets in the .env file if it’s used client-side. Use environment variables responsibly.

Conclusion

Environment variables are a vital part of any web application. With Vite’s simplicity and React.js’s flexibility, you can seamlessly integrate environment-specific configurations into your project. Follow this guide to keep your app secure, maintainable, and ready for any environment.

Ready to implement environment variables in your React.js app with Vite? Let’s get started!

If you found this tutorial helpful, check out more on my YouTube channel for in-depth guides on React, Vite, and beyond. 🚀

Top comments (0)