Search code examples
javascripttypescriptenvironment-variablesvite

How to use an .env variable in Vite with Typescript?


I've an .env file with the following variable:

VITE_GIPHY_KEY=abcdfg

And I'm trying to use that .env variable in src/main.ts like this:

console.log(import.meta.env.VITE_GIPHY_KEY);

I get undefined in the console. How can I use .env variables in Vite with TS?


Solution

  • First I renamed .env to .env.local

    Second, only variables prefixed with VITE_ are exposed to your Vite-processed code. Example:

    VITE_SOME_KEY=123
    DB_PASSWORD=foobar
    
    console.log(import.meta.env.VITE_SOME_KEY) // 123
    console.log(import.meta.env.DB_PASSWORD) // undefined
    

    Source: https://vitejs.dev/guide/env-and-mode.html#env-files