Raúl Peñate
Raúl Peñate

Reputation: 607

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?

Upvotes: 2

Views: 9878

Answers (2)

chimpsociety
chimpsociety

Reputation: 81

I cannot fully explain why, but what was working for me when facing the same issue is to make sure of 2 things:

  1. All env variables need to have the prefix VITE_ (you have that)
  2. the .env file needs to be in the in the root directory of the project
    (Yours seem to be placed in the /src folder, which is one level below root)

I assume the reason that .env.local works must be because the builder expects the .env in the absolute path, but the .env.locals in relative paths to root. I am sure someone more knowledgable can give a more detailed answer.

Per the docs, there is also a envDir variable that can be set. I assume this will change where the builder looks for .env files. E.g. if you want to have all your .env files in a folder like /envs.

Upvotes: 2

Raúl Peñate
Raúl Peñate

Reputation: 607

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

Upvotes: 3

Related Questions