Typing Vite's Environment Variables

Door-check’s build now runs npm run check first, so a type error stops it. The next change needs a value from outside the code. When a guest isn’t on the door list, Rosa Delgado’s ushers send them to the box office’s walk-up page. That page’s address differs between testing and the night of the event, so you’ll keep it in a .env file.

In this lesson, you’ll give the checker Vite’s types, then declare door-check’s own setting so the checker knows its name and type. Start by reading the address and running the check.

Load Vite’s Types

The checker knows JavaScript and the browser, but not Vite. When it serves or builds the page, Vite hands each .env variable whose name starts with VITE_ to the page code on import.meta.env. Create .env in door-check’s root folder:

Language: Text Filename: .env
VITE_BOX_OFFICE_URL=https://box-office.lanternstreet.example

In index.html, add a link under the <ul id="door-list"></ul> line:

Language: HTML Filename: index.html
    <p>Not on the list? Send them to the <a id="box-office">box office</a>.</p>

At the end of src/main.ts, put the address in the link’s href:

Language: TypeScript Filename: src/main.ts
const boxOfficeUrl = import.meta.env.VITE_BOX_OFFICE_URL;
const boxOffice = document.querySelector("#box-office");
boxOffice?.setAttribute("href", boxOfficeUrl);

Run the check:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit -p tsconfig.json && tsc --noEmit -p scripts/tsconfig.json

src/main.ts:11:34 - error TS2339: Property 'env' does not exist on type 'ImportMeta'.

11 const boxOfficeUrl = import.meta.env.VITE_BOX_OFFICE_URL;
                                    ~~~

Found 1 error in src/main.ts:11

The checker stops at env and never gets as far as the variable’s name. import.meta is part of JavaScript, but env is Vite’s addition. The page config’s "lib" and "types" don’t mention Vite, so the checker has never seen env. Vite ships those types in vite/client. Create src/vite-env.d.ts with one line:

Language: TypeScript Filename: src/vite-env.d.ts
/// <reference types="vite/client" />

That line is a triple-slash directive, a comment that tsc reads as an instruction to load a package’s types. Only the page config includes src/, so the export script doesn’t get those types.

Run npm run check again, and it passes. The same types cover Vite’s special imports, such as images. Save the theater’s lantern logo as src/lantern.svg:

```svg filename=”src/lantern.svg”

Import it on the first line of `src/main.ts`, and add it to the page at the end:

```ts filename="src/main.ts"
import lanternUrl from "./lantern.svg";
// ...
const logo = document.createElement("img");
logo.src = lanternUrl;
logo.alt = "Lantern Street Theatre";
document.body.prepend(logo);

The check passes because vite/client types lanternUrl as a string, and src accepts a string. The type only says it’s an address to load the image from. That’s a path to the file or, for a small file, a data: URL with the image inside, and Vite chooses which.

Declare Door-Check’s Variables

The check passes, but the checker knows nothing about VITE_BOX_OFFICE_URL. Vite’s ImportMetaEnv, the type of import.meta.env, allows any name and types its value as any. You can declare the variable’s name and type.

Vite declares ImportMetaEnv as an interface, and two interfaces with the same name merge into one. That works only while vite-env.d.ts has no import or export of its own, because either would make the file’s declarations local to it. Add these under the directive:

Language: TypeScript Filename: src/vite-env.d.ts
/// <reference types="vite/client" />

interface ViteTypeOptions {
  strictImportMetaEnv: unknown;
}

interface ImportMetaEnv {
  readonly VITE_BOX_OFFICE_URL: string;
}

Read it from the bottom. ImportMetaEnv gains door-check’s variable as a readonly string, since the page never sets it. Vite’s types check only whether ViteTypeOptions has a property named strictImportMetaEnv, whatever its type, so unknown is the convention. With strictImportMetaEnv, import.meta.env allows only the names you declare, plus Vite’s own, such as MODE.

Run npm run check, and it passes, now with a declared type for the address. An undeclared name, such as import.meta.env.VITE_DOORS_OPEN, fails with error TS2339: Property 'VITE_DOORS_OPEN' does not exist on type 'ImportMetaEnv'.

The button below opens a mentor chat where you can explore which names the checker now accepts and try your own:

So the switch limits the names your code may read, but nothing checks the declaration against .env. Vite writes each value into the page after the types are gone, so if .env lacks the line, the check still passes and the page gets undefined.

See the box office and logo URLs in the browser: run npm run dev, open the address it prints, and inspect the page in the Elements panel. The link’s href is the address from .env. The logo’s src is a data:image/svg+xml,... URL, because Vite inlined the small SVG. It’s still a string, but this one carries the image itself.

Then delete the line from .env and save. Vite restarts, so reload the page. The href is now "undefined". Put the line back, and add each new variable to .env and ImportMetaEnv together.

Check Your Understanding

  1. Mei Chen wants the box office’s phone number shown too. A volunteer adds VITE_BOX_OFFICE_PHONE to .env and src/main.ts, and npm run check reports error TS2551: Property 'VITE_BOX_OFFICE_PHONE' does not exist on type 'ImportMetaEnv'. Did you mean 'VITE_BOX_OFFICE_URL'? Why, and should they follow the suggestion?
  2. Liam deletes the directive from src/vite-env.d.ts, since the file declares ImportMetaEnv itself. What does npm run check report?
  3. Someone builds door-check with a .env that’s missing VITE_BOX_OFFICE_URL. Does the build’s check pass, and where does the link point?
  1. strictImportMetaEnv allows only declared names, and the new one isn’t declared. The suggestion is only the nearest declared name, and following it would show the box office’s address instead of its phone number. Add readonly VITE_BOX_OFFICE_PHONE: string; to ImportMetaEnv, and keep the switch on.
  2. npm run check reports two errors: first Cannot find module './lantern.svg' for the logo’s import, then Property 'env' does not exist on type 'ImportMeta'. again. Both the .svg type and import.meta.env come from vite/client. Your interface only adds to Vite’s.
  3. The check passes because it reads the declaration and never opens .env. Vite writes undefined into the bundle, so the href becomes the text "undefined". That’s a relative address the browser resolves against the page’s own address. On the dev server, the link points to http://localhost:5173/undefined.

Door-check now has both configs, a checked build, and a typed box office address. Next, in Exercise: Set Up the Door-Check Project, you’ll put that setup together the way a new volunteer would find it.

Become a Member to join the conversation.