106

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Mohamed Fadl
  • 1,303
  • 2
  • 8
  • 10
  • 4
    Only those with VITE_ prefix will be visible inside your JS / Vue code. Check their documentation https://vitejs.dev/guide/env-and-mode.html – Joel Chu Apr 28 '23 at 01:03

11 Answers11

113

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()]
    }); 
};
user16547619
  • 199
  • 1
  • 4
Mahmoud
  • 1,703
  • 1
  • 9
  • 13
  • Thanks for the example, I'm using Vite with Svelte (not svelteKit) to generate code for browsers and obviously I misinterpreted the Vite documentation, I expected that .env was always included automatically, since it doesn't work and adding loadEnv in the config works i would say that's not the case. – Alex Aug 21 '22 at 12:24
  • 8
    The linked docs (https://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 – Larry Sep 30 '22 at 19:52
  • Good catch. The doc for `loadEnv` (https://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_")};` – AymKdn Jan 31 '23 at 10:33
  • thank you, I just had to add `VITE_` at the beginning. – Gangula Aug 07 '23 at 18:13
86

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
Wonkledge
  • 1,732
  • 7
  • 16
39

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)
James Lawruk
  • 30,112
  • 19
  • 130
  • 137
  • 3
    Alternatively, setting `envDir` option in `vite.config.ts`: ```typescript export default defineConfig({ plugins: [react()], envDir: './src/environments' }) ``` – bene-we Oct 04 '22 at 08:07
  • 2
    What tripped me up was not realizing I had created my `.env.development` file in the `src` folder instead of the root dir – bishop Jan 03 '23 at 11:57
  • 1
    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](https://v2.vitejs.dev/config/#root). @bishop I presume you have `root: "./src"` set. – hendalst Jan 31 '23 at 07:48
  • 1
    I just wasted two hours because my env file was outside my project folder – ben_g_123 Apr 22 '23 at 12:46
9

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.

Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
1

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.

kimdw9983
  • 21
  • 4
1

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.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
0

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

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Francisco
  • 21
  • 2
0

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>
}
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Blazexsam
  • 1
  • 1
0

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.
Guy T
  • 1
  • 1
  • 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](/help/how-to-answer). – Community Jul 12 '23 at 18:56
  • 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](https://meta.stackoverflow.com/q/421831). 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](https://stackoverflow.com/help/gpt-policy). – tchrist Jul 15 '23 at 12:34
0

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.
-4

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
  • 1
    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](/help/how-to-answer). – Community May 18 '23 at 18:04
  • 1
    Did you notice that the formatting in your question is completely broken? Please fix it – Moritz Ringler May 20 '23 at 07:55