“Uncaught ReferenceError: process is not defined” in Vite — Here’s How to Fix It

VAIBHAV NIRMAL
2 min readNov 7, 2024

--

If you’ve been working with Vite you might run into the error:

“Uncaught ReferenceError: process is not defined”

This happens because Vite works a bit differently than older tools like Create React App (CRA). In CRA, you’d typically access environment variables using process.env, but in Vite, that’s not the case anymore. Let’s talk about how to fix this issue and get your environment variables working properly.

Why Does This Error Happen?

In older setups, we’d access environment variables like this:

const apiUrl = process.env.REACT_APP_API_URL;

But in Vite, process.env doesn’t work. Instead, Vite uses a different way to handle environment variables — import.meta.env. When you try to use process.env in a Vite project, you’ll see that annoying error: "Uncaught ReferenceError: process is not defined".

The Fix: Use import.meta.env in Vite

To fix this, you’ll want to switch from process.env to import.meta.env.

Prefix Your Variables with VITE_

Vite requires that all environment variables you want to use in the frontend (client-side) have the prefix VITE_.

VITE_API_BASE_URL=http://localhost:8080/api/v1

2. Accessing Environment Variables

Once you’ve got your variables set up with the VITE_ prefix, you can access them in your code like this:

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

That’s it! You’re now using import.meta.env to access your environment variables instead of process.env.

example a service to call your API:

Create a .env file with the variable:

VITE_API_BASE_URL=http://localhost:8080/api/v1

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

That’s all there is to it!

Note: This solution works for all vite apps used with any framework.

Thanks for reading: Uncaught ReferenceError: process is not defined

#vite #react #vite #jsx

--

--

VAIBHAV NIRMAL
VAIBHAV NIRMAL

Written by VAIBHAV NIRMAL

Hi there.. This is Vaibhav. A Passionate Software Developer. I'm all about creating cool stuff with code.

No responses yet