190

I want to load environment variables from the .env file using Vite

I used the import.meta.env object as mentioned in Docs

.env file:

TEST_VAR=123F

when trying to access this variable via the import.meta.env -> import.meta.env.TEST_VAR it returns undefined.

so, how can I access them?

3

18 Answers 18

213

According to the docs, you need to prefix your variables with VITE_:

To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.

If you are trying to access env vars outside your app source code (such as inside vite.config.js), then you have to use loadEnv():

import { defineConfig, loadEnv } from 'vite';

export default ({ mode }) => {
    // Load app-level env vars to node-level env vars.
    process.env = {...process.env, ...loadEnv(mode, process.cwd())};

    return defineConfig({
      // To access env vars here use process.env.TEST_VAR
    });
}

For SvelteKit

// vite.config.js

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig, loadEnv } from 'vite';

/** @type {import('vite').UserConfig} */
export default ({ mode }) => {
    // Extends 'process.env.*' with VITE_*-variables from '.env.(mode=production|development)'
    process.env = {...process.env, ...loadEnv(mode, process.cwd())};
    return defineConfig({
        plugins: [sveltekit()]
    }); 
};
Sign up to request clarification or add additional context in comments.

9 Comments

The linked docs (vitejs.dev/guide/env-and-mode.html#env-files) don't mention using loadEnv - they seem to imply that the presence of .env in the root will load VITE_ env vars implicitly. loadEnv seems to be required, but I don't see it in the docs O.o. Vite version: 3.1.4
Good catch. The doc for loadEnv (vitejs.dev/guide/api-javascript.html#loadenv) permits to see that we can change the prefix: process.env = {...process.env, ...loadEnv(mode, process.cwd(), "VUE_")};
Does anyone know how to access production environment variables from a cloud deployment? I assume I'll need a conditional statement to seek them, but is there a particular reference for them? I.e. in python it's os.environ.
just remember to restart your server.. was stuck on that.
This answer is outdated and hence misleading. The correct answer these days is the one below. See docs here.
|
144

if you want to access your env variable TEST_VAR you should prefix it with VITE_

try something like

VITE_TEST_VAR=123f

you can access it with

import.meta.env.VITE_TEST_VAR

7 Comments

but with import.meta.env I get an error that the meta name is not found
I do not know why it throws an error, but // @ts-ignore on the line above helps 🤫
@EliZatlawy no you can't
i'm here just cause, in fact, does not work
|
82

Here are three mistakes/gotchas that tripped me up.

  • Ensure the .env files are in the root, not the src directory. The filename .env and/or .env.development will work when running locally.
  • Restart the local web server for the variables to appear: npm run dev
  • Prefix the variables with VITE_ (as already mentioned by Mahmoud and Wonkledge)

7 Comments

Alternatively, setting envDir option in vite.config.ts: typescript export default defineConfig({ plugins: [react()], envDir: './src/environments' })
What tripped me up was not realizing I had created my .env.development file in the src folder instead of the root dir 🙈
Note that when the vite docs mention root, they mean the project root (i.e. where index.html is), and not the top-level project folder. These are not the same if you have set the root option. @bishop I presume you have root: "./src" set.
I just wasted two hours because my env file was outside my project folder
Another gotcha: I had comments in my .env file so vite didn't load the .env file.
|
27

Another solution that worked for me is to manually call dotenv.config() inside the vite.config.js. That will load variables from .env (all of them!) into process.env:

import { defineConfig } from 'vite'
import dotenv from 'dotenv'

dotenv.config() // load env vars from .env

export default defineConfig({
  define: {
    __VALUE__: `"${process.env.VALUE}"` // wrapping in "" since it's a string
  },
  //....
}

where .env file could be:

VALUE='My env var value'

See the demo.

3 Comments

How do you install "dotenv" in a Vite/React project? I tried npm install dotenv but still I get errors
Dont undestand how your import VALUE, there is no this variable
Vite uses dotenv under the hood. Wouldn't loadEnv achieve same goal?
11

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

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 {
    plugins: [react()],
    // vite config
    define: {
      ...Object.keys(env).reduce((prev, key) => {
        const sanitizedKey = key.replace(/[^a-zA-Z0-9_]/g, "_");

        prev[`process.env.${sanitizedKey}`] = JSON.stringify(env[key]);

        return prev;
      }, {}),
    },
  }
})

You can use this above code (sanitized) and issue will be resolved now you can use process.env.VARIALBE_NAME like this.

Comments

8

I got .env to work using:

const env = await import.meta.env;
export const version = (env.VITE_APP_VERSION);
export const buildDate = (env.VITE_APP_BUILD_TIME);

The key thing was await.

This will also work in .env.development / cmd: VITE_APP_VERSION=development vite

1 Comment

Where do you configure this? In the vite config file?
7

As stated in docs, you can change the prefix by mdoify envPrefix.

Env variables starting with envPrefix will be exposed to your client source code via import.meta.env.

So changing it to TEST_ will also work.

export default defineConfig({
...
  envPrefix: 'TEST_',
...
})

You can change this option whatever you want except for empty string('').

envPrefix should not be set as '', which will expose all your env variables and cause unexpected leaking of sensitive information. Vite will throw an error when detecting ''.

So overriding the dotenv config directly to remove prefix completely could be an inappropriate action as all fields written in env would send directly into the client.

1 Comment

Best answer ever! for CRA for instance, use envPrefix: 'REACT_APP_' and it will pick things up from your .env file.
3

Please do not use the best voted answer snippet as it is dangerous/wrong.

Current (v5.3.1) vite's loadEnv implementation is created such that if you mutate process.env it will not update the value if you change .env file, causing all sorts of problems in development mode.

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

// https://vitejs.dev/config/
export default ({ mode }) => {
  // Load app-level env vars to node-level env vars. !!! BUT DON'T REASSIGN it to process.env (notice `const loadedEnv =`) !!!
  const loadedEnv = { ...process.env, ...loadEnv(mode, process.cwd()) };

  return defineConfig({
    // To access env vars here use loadedEnv.TEST_VAR
  });
};

You can easily reproduce my findings, just change loadedEnv to process.env, log it, and update .env values without restarting the vite server.

I hope this saves someone an hour.

Comments

1

It is actually pretty easy to use environment variable if you used vite for generating react boiler plate code.

All you have to do is prefix all of your environment variables with VITE_. example: Suppose you have env variable called MY_API = xyz then change it to: VITE_MY_API = xyz

then simply use import.meta.env.VITE_MY_API.

const App = () => {
   return <div>{import.meta.env.VITE_MY_API}</div>
}

Comments

1

I had the same problem and the issue was that I had created my .env.local file in the src folder instead of the root dir, if you change that it will work just fine calling the variable as you are doing it import.meta.env

Comments

1

The issue is that import.meta.env.VITE_API is returning undefined. To troubleshoot, follow these steps:

  • Save the .env file at the root of your project.
  • Check the variable name in the .env file matches what you're accessing in your code.
  • Restart the Vite development server to apply changes from the .env file.
  • Ensure the dotenv configuration is correctly set up in your vite.config.js.
  • Verify you're using a Vite version that supports import.meta.env.
  • Confirm that you're importing and using import.meta.env.VITE_API correctly in your code. If you've followed these steps and still face issues, provide more context or code snippets for further assistance.

Comments

1

First, if you're trying to access an env. variable in client side code, add VITE_ prefix to your env. variable in the .env file.

What tripped me was the difference between npm run dev and npm run build in vite 4. Looks like that got resolved in vite 5.

In dev mode, I was getting undefined. To get it working on both modes(dev and build==prod), you can add this code in any js file:

    if (import.meta.env.DEV) {
        // side effect necessary to have env. variables ready when running `npm run dev`.
        (async () => await import.meta.env)();
    }

As a plus, here's a convenient method for getting env. variables' value

   /**
     * Convenient method that gets the value of environment variables
     * @param {string} name name of the env. var
     * @returns {string} value of the env. var
     */
   const getEnvVar = name => import.meta?.env?.[name];

Comments

1

First, you have to prefix your environment variables with VITE_ in the .env otherwise vite wouldn't be able to read it.

Then in the vite.config.js file, you can add the code below, and you would be able to use process.env.{variableName} without need to prefix VITE

import { defineConfig, loadEnv } from "vite";

// https://vite.dev/config/

export default defineConfig(({ mode }) => {
    // If you want to use the environment variables without prefix VITE_
    // EX: process.env.API_KEY
    const updatedEnv = Object.fromEntries(
        Object.entries(loadEnv(mode, process.cwd())).map(([key, val]) => [
            key.replace(/^VITE_/, ""),
            val,
        ])
    );

    // If you want to use the environment variables with prefix VITE_
    // EX: process.env.VITE_API_KEY
    // const updatedEnv = loadEnv(mode, process.cwd(), 'VITE_');
    return {
        define: {
          'process.env': updatedEnv
        },
        // other configs like plugins, ...etc
    };
});

Comments

0

I had the same issue and solved it by running

pnpm add dot-env
pnpm add -S  dotenv-webpack. 

Lastly I made sure that I added VITE_ before the name I had for my environment variable, that is from MAP_API_KEY to VITE_MAP_API_KEY.

Comments

0

If you came here to find out how to put actual environment variables into Vite, via the .env file (i.e. those defined in your operating system), then thus:

MY_VAR=${MY_ACTUAL_EN_VAR}

That will load the MY_ACTUAL_VAR into vite's MY_VAR. Access in the normal way import.meta.env.MY_VAR)

If you'd like to add a default value when it's not defined add ":-" then the default, thus:

MY_VAR=${MY_ACTUAL_VAR:-a_fallback_value_123}

Comments

-1

I faced a similar issue, so here are a few suggestions to address it when using .env with Vite:

  1. First, try directly pasting the source of the key. If it works, it's likely an issue with your .env configurations.
  2. Place the .env files in the root directory, not the src directory. Regardless of whether you choose .env or .env.development as the filename, it should work when running locally.
  3. After modifying the .env files, be sure to restart the local web server (npm run dev) to ensure that the updated variables take effect.
  4. To ensure proper recognition, remember to prefix the variables with VITE_. This step is crucial for their correct functionality.

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
This answer looks like it was generated by an AI (like ChatGPT), not by an actual human being. You should be aware that posting AI-generated output is officially BANNED on Stack Overflow. If this answer was indeed generated by an AI, then I strongly suggest you delete it before you get yourself into even bigger trouble: WE TAKE PLAGIARISM SERIOUSLY HERE. Please read: Why posting GPT and ChatGPT generated answers is not currently allowed.
-1

If anyone is still struggling with this, you may need to import the dotenv library for it to work:

 npm install dotenv --save

This solved the issue in my case.

Comments

-5

To load environment variables from.env file using Vite, you need to follow these steps:

  Install the dotenv library with npm:
  npm install dotenv
Create a.env file in the root directory of your project and add your environment variables to it.
For example: #contents of .env
VITE_API_KEY = my - secret - api - key
Prefix your environment variables with VITE_ to make them accessible to your Vite - processed code.For example:
  VITE_API_KEY = my - secret - api - key
Import the environment variables in your code using the
import.meta.env object.For example:
  // import the environment variable
  const apiKey =
    import.meta.env.VITE_API_KEY;

// use the environment variable
console.log(apiKey); // prints my-secret-api-key
Restart the server after making changes to the.env file.
For more information, you can refer to the official documentation: https: //vitejs.dev/guide/env-and-mode.html

3 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Did you notice that the formatting in your question is completely broken? Please fix it
This works for DEV but how do you get env variable for production -- (npm run build). Do you have to add .env to GIT?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.