Env Variables and Modes

    • import.meta.env.MODE: {string} the mode the app is running in.

    • import.meta.env.PROD: {boolean} whether the app is running in production.

    • import.meta.env.DEV: {boolean} whether the app is running in development (always the opposite of import.meta.env.PROD)

    During production, these env variables are statically replaced. It is therefore necessary to always reference them using the full static string. For example, dynamic key access like import.meta.env[key] will not work.

    It will also replace these strings appearing in JavaScript strings and Vue templates. This should be a rare case, but it can be unintended. There are ways to work around this behavior:

    • For JavaScript strings, you can break the string up with a unicode zero-width space, e.g. 'import.meta\u200b.env.MODE'.

    Vite uses to load additional environment variables from the following files in your project root:

    Loaded env variables are also exposed to your client source code via import.meta.env.

    To prevent accidentally leaking env variables to the client, only variables prefixed with are exposed to your Vite-processed code. e.g. the following file:

    1. DB_PASSWORD=foobar
    2. VITE_SOME_KEY=123

    Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY to your client source code, but DB_PASSWORD will not.

    SECURITY NOTES

    • Since any variables exposed to your Vite source code will end up in your client bundle, VITE_* variables should not contain any sensitive information.

    IntelliSense

    To achieve, you can create an env.d.ts in directory, then augment ImportMetaEnv like this:

    By default, the dev server (serve command) runs in development mode, and the build command runs in production mode.

    This means when running vite build, it will load the env variables from .env.production if there is one:

    1. # .env.production
    2. VITE_APP_TITLE=My App

    In your app, you can render the title using import.meta.env.VITE_APP_TITLE.

    However, it is important to understand that mode is a wider concept than just development vs. production. A typical example is you may want to have a “staging” mode where it should have production-like behavior, but with slightly different env variables from production.

    You can overwrite the default mode used for a command by passing the --mode option flag. For example, if you want to build your app for our hypothetical staging mode:

    And to get the behavior we want, we need a .env.staging file:

    1. # .env.staging
    2. VITE_APP_TITLE=My App (staging)