avatarAdam Fisher / fisher king (@therightstuff)

Summary

The article discusses the process of passing environment variables to a React application using Vite, emphasizing the necessity of prefixing custom environment variables with VITE_.

Abstract

The author of the article shares their experience with configuring environment variables in a React application using Vite. Initially, the author found that the documentation did not provide clear guidance, leading to unsuccessful attempts to modify the vite.config.ts file. The author discovered that environment variables needed to be prefixed with VITE_ to be automatically loaded and passed through to the app. This insight was gained after unhelpful suggestions from the documentation and unsuccessful attempts to access the variables in the app's console. The article concludes with a demonstration of how to correctly define and access environment variables in both development and production modes, and notes that these variables do not need to be included in the configuration file if not required there.

Opinions

  • The author suggests that the Vite documentation may be outdated or unclear regarding the use of environment variables.
  • Frustration is conveyed about the initial lack of success in using the documented methods for environment variables.
  • The author provides a correction to their initial approach, highlighting the importance of the VITE_ prefix for environment variables.
  • The author endorses a third-party AI service, ZAI.chat, as a cost-effective alternative to ChatGPT Plus (GPT-4), indicating a positive opinion of this service.

Passing Vite Environment Variables Into Your React App

Photo by Pankaj Patel on Unsplash

Here are my sample .env files for my React app:

.env

MY_FLAG=some dev value

.env.production

MY_FLAG=some prod value

I don’t know if the documentation just isn’t up-to-date, but none of the suggestions for modifying vite.config.ts worked for me. [EDIT: according to this StackOverflow answer I was looking at the wrong documentation, I needed this]

This is the unhelpful situation I found myself in before guessing desperately:

import react from '@vitejs/plugin-react';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';

// https://vitejs.dev/config/
export default defineConfig(({command, mode} : ConfigEnv) => {
    console.log(`configuring vite with command: ${command}, mode: ${mode}`); // command: serve, mode: development
    // suppress eslint warning that process isn't defined
    // eslint-disable-next-line
    const cwd = process.cwd();
    console.log(`loading env from ${cwd}`);
    // load all entries in the .env files that are prefixed with VITE_
    const env = {...loadEnv(mode, cwd, 'MY_')};
    console.log(`env: ${JSON.stringify(env)}`);
    return {
        base: './',
        build: {
            ...
        },
        define: {
            // this is supposed to make the env vars available to the react app
            'process.env': env,
            // or maybe this?
            __APP_ENV__: JSON.stringify(env),
        },
        plugins: [react()],
        server: {
            ...
        },
    };
});

When building or running the server, the desired values were printed in the terminal, but when I printed out the contents of the injected environment variables in the app’s console with the following:

console.log(`env`, import.meta.env);

Only the default environment variables were found:

{
    "BASE_URL": "/",
    "MODE": "development",
    "DEV": true,
    "PROD": false,
    "SSR": false
}

It turns out that the loadEnv works nicely for loading environment variable values that you want to use in the config file itself, but if you want to pass them through to the app you *have* to prefix them with VITE_.

When the environment variables are prefixed with VITE_, they’re automatically loaded and passed through to the app.

.env

VITE_MY_FLAG=some dev value

.env.production

VITE_MY_FLAG=some prod value

Now, when running in dev mode I’m seeing:

{
    "VITE_MY_FLAG": "some dev value",
    "BASE_URL": "/",
    "MODE": "development",
    "DEV": true,
    "PROD": false,
    "SSR": false
}

And unless you need those VITE_-prefixed variables in your configuration file itself, you can just drop them entirely:

import react from '@vitejs/plugin-react';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';

// https://vitejs.dev/config/
export default defineConfig(({command, mode} : ConfigEnv) => {
    console.log(`configuring vite with command: ${command}, mode: ${mode}`); // command: serve, mode: development
    return {
        base: './',
        build: {
            ...
        },
        plugins: [react()],
        server: {
            ...
        },
    };
});

If you enjoyed this article, consider trying out the AI service I recommend. It provides the same performance and functions to ChatGPT Plus(GPT-4) but more cost-effective, at just $6/month (Special offer for $1/month). Click here to try ZAI.chat.

Vite
React
Environment Variables
Configuration
Recommended from ReadMedium