How to load environment variables from .env file using Vite

243.3k views Asked by At

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?

14

There are 14 answers

6
Mahmoud On BEST ANSWER

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()]
    }); 
};
6
Alexandre LEROY On

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
4
James Lawruk On

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)
0
Dmitri Pavlutin On

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.

0
kimdw9983 On

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.

0
Tabot Charles Bessong On

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.

0
Francisco On

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

0
Blazexsam On

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>
}
2
rabit ebibi On

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

2
Guy T On

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.
0
Alhdrin Gungon On

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.
0
ian On

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

0
sigma1510 On

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.

0
Code_freak On

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) => {
        prev[`process.env.${key}`] = JSON.stringify(env[key])
        return prev
      }, {}),
    },
  }
})

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