Vite is failing to load the specified values from the .env file

In the context of utilizing React, Typescript, Vite, and Yarn in my project, I am facing an issue with defining my backend URL as a constant in my .env file. Despite setting it up correctly, the frontend is still making requests to localhost:3036 instead of using the specified backend URL running on port 8080.

Initially, I defined the backend URL in my .env file like this:

NODE_ENV=development
VITE_BACKEND_URL=http://localhost:8080

Although I tried troubleshooting by prefixing it with VITE and following the instructions provided in the documentation, such as adding configuration in my vite.config.ts file, the problem persisted.

Upon further investigation, I attempted to access the backend URL using import.meta.env.VITE_BACKEND_URL, but encountered errors indicating that import.meta.env was undefined. Similarly, when checking process.env, it displayed

BACKEND_URL from process.env: undefined
.

The method through which I make requests using the backend URL involves configuring Axios instances, which should ideally pick up the value set in the .env file. Running commands like yarn build and yarn dev while setting the NODE_ENV and BACKEND_URL also seem to function as expected, except for some CORS issues.

Despite verifying that the environment variables are accessible post-sourcing the .env file, the backend URL is not being recognized at the top-most level where vite loads the .env file. Any guidance or insights on resolving this issue would be greatly appreciated.

Answer №1

I have encountered a situation where I was unable to create a complete reproducible example, but I have an understanding of what might be happening. It's a mistake that I have made in the past.

Imagine you have an environment file like this:

VITE_BACKEND_URL=http://localhost:8080

You can refer to the documentation on Using Environment Variables in Config and then use define to make global constant replacements

import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ command, mode }) => {
  // Load env file based on `mode` in the current working directory.
  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
  const env = loadEnv(mode, process.cwd(), '')
  return {
    // vite config
    define: {
      __VITE_BACKEND_URL__: JSON.stringify(env.VITE_BACKEND_URL),
    },
  }
})

According to the documentation, if you are using TypeScript, you will need to declare your global constants as well

// vite-env.d.ts
declare const __VITE_BACKEND_URL__: string

:warning: Keep in mind that this method is different from using process.env. You can still access environment variables through process.env if they have been set.

If you run something like this:

NODE_ENV="development" BACKEND_URL="http://localhost:8080" yarn dev

You will make the environment variables accessible through process.env, but this is not equivalent to declaring a global constant using vite.


What your code may be doing (my assumption)

// destructure process.env and override the global variables defined by vite
const {
  NODE_ENV,
  VITE_BACKEND_URL,
} = process.env;

// If loadEnv was used and certain environment variables were not explicitly set, this will be undefined
console.log('BACKEND_URL from process.env:', VITE_BACKEND_URL)

// everything below will just use what was set above
const env = {
  NODE_ENV: NODE_ENV || 'development',
  BACKEND_URL: VITE_BACKEND_URL,
};

export type ProjectEnv = typeof env;

export default () => ({
  data: env,
});

Instead, you should stick to using global constants

console.log('BACKEND_URL *not* from process.env:', __VITE_BACKEND_URL__)

To avoid confusion, follow the convention of using double underscores when defining globals.

If you prefer to use process.env, then ensure that your variables in .env are set in the process environment. It seems like you are not doing this currently.

Another approach is to utilize import.meta, but I would need to revisit it to recall the specifics, and it may not explain the issue in your current setup.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript class validator that validates based on varying data types

Currently, I am utilizing TypeORM and seeking ways to dynamically set the validation fields based on the value of another field. Let me illustrate this using my DTO model: import { IsString, IsOptional, IsNumber, IsEnum, IsObject, IsBoolean, ValidateNeste ...

Could a tslint rule be implemented in Typescript classes to ensure method return types are enforced?

After diving into the tslint rules here, it seems that although the typedef rule's call-signature option might be close to what I need, it doesn't address the absence of a return type. Is there a specific rule (if one exists) that can enforce re ...

When utilizing Typescript to develop a form, it is essential to ensure that the operand of a 'delete' operator is optional, as indicated by error code ts(279

Can someone help me understand why I am encountering this error? I am currently working on a form for users to submit their email address. export const register = createAsyncThunk< User, RegisterProps, { rejectValue: ValidationErrors; } > ...

The data type 'unknown' cannot be assigned to the type 'any[]', 'Iterable<any>', or (Iterable<any> & any[])

I have been working on creating a custom search filter in my Angular project, and it was functioning properly. However, I encountered an error in my Visual Studio Code. In my previous project, everything was working fine until I updated my CLI, which resul ...

Navigating through HTML code - a beginner's guide

I have a variable containing the following HTML code: let htmlDocument = '<div id="buildings-wrapper"> \ <div id="building-info"> \ <h2><span class="field-content">Britney Spears' House</span></ ...

What are some strategies for encouraging tools to embrace TypeScript's exhaustiveness checking with minimal reliance on comments?

My coding style involves incorporating exhaustiveness checking in a lot of the code I write. In the following code snippet, I intentionally introduce a type error in the line with _exhaustivenessCheck if there are additions made to the UnitOfTime union. W ...

Three.js - spinning texture applied to spherical shape

Would it be possible to rotate a loaded texture on a sphere geometry in Three.js without rotating the object itself? I am seeking a way to rotate just the texture applied to the material. Imagine starting with a sphere like this: https://i.sstatic.net/Ol3y ...

Utilizing type arguments in JSX components when applying withStyles

When working with React and material-ui, I am attempting to create a JSX component that can accept generic parameters while also utilizing the withStyles Higher Order Component (HOC) to inject styles. The initial approach looked something like this: cons ...

Utilizing the progress or meter tag in combination with a reactive value

Within my Vue class-based component, I am aiming to utilize a reactive value to showcase real-time progress changes using either a <progress> or <meter> tag. To achieve this, I have defined a variable that contains an initial base value: perce ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

Implementing Angular - Injecting a component dynamically into another component

Currently, I am working on developing a small UI components framework for my personal use and enjoyment. One of the components I'm working on is a Tab component. To test this component, I need to dynamically inject another component (TabContainerCompo ...

Intercepting Bootstrap 4 modal display and conceal events using Typescript

While working on integrating a modal with the id myModal, I am attempting to connect it with events that trigger when it is shown and closed. I referred to the documentation at and implemented the following in my modal component: this.modalElement = docu ...

Unable to set intricate information to array variable in Angular 6

I have successfully implemented a method for retrieving data from an HTTP request, and it is functioning well, returning a complex list of data. https://i.sstatic.net/Hxpz2.png However, my concern arises when I try to assign the returned list to a variab ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

Struggling with incorporating GlobalStyles in the app.tsx file

I have been working with next13 and styled-components. Initially, everything seemed fine in my file globalStyles.ts, and all was functioning perfectly. However, I started encountering errors related to the import of <GlobalStyles/>. Specifically, th ...

What is the best way to populate an Angular variable in Ionic following a subscription?

Currently, I am in the process of retrieving data from a server and displaying it on an Ionic page. I have successfully fetched the data without any issues and verified it in the console. However, how do I proceed once the server returns the data to me? T ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

Having difficulty removing new or existing lines on StackBlitz

I attempted to experiment with React on StackBlitz, but I encountered a problem where I couldn't delete any lines of code. It seems that while I can add new lines of code, deleting them is not an option. Even when logging in with GitHub, the issue per ...

Issue with RouterLink not recognizing QueryParams

I have encountered an issue where dynamically generated URLs with queryParams inside [routerLink] are breaking routes. For example: this.url = '/question/ask?details=1' <a [routerLink]="url"> {{ data.name }}</a> Upon mouseover, the ...