Using dotenv variables with Sveltekit

Vite and hence Svletekit use dotenv: a module that loads variables from a .env file into process.env. Basically a file named .env is placed at the root of the project (this is the default file location and can be modified). This allows for enviroment specific information and is often used for keys or passwords. Best practice dictates that the file is gitignored so sensitive information can be kept away from public repositories or other unprotected locations.

Vite documentation provides us with this handy table:

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Rules of specificity apply and the more specific the filename the higher priority the file will be given. This means you can have a .env file that would be overwritten by a .env.production file.

The variables can be accessed using

import.meta.env

In a sveltekit application (using Vite) we can therefore have logic based on development or production mode :

{
  BASE_URL: '/',
  MODE: 'development',
  DEV: true,
  PROD: false,
  SSR: true
}

We can also create secret keys by adding them to a .env file. We can add

MY_KEY="SHHH!!IMASECRET!"
VITE_MY_KEY="IMIINDOTENV"

and can overwrite this key in a file called .env.production.

VITE_MY_KEY="IMIINDOTENVPRODUCTION"

And we can access any key prefixed by VITE_ in our source code

{
  VITE_MY_KEY: 'IMIINDOTENV',
  BASE_URL: '/',
  MODE: 'development',
  DEV: true,
  PROD: false,
  SSR: true
}

For example this file has a variable

const { VITE_MY_KEY } = import.meta.env;

⚠️ Note: I can’t access MY_KEY from this context

In development mode I see : IMIINDOTENV

(You’ll have to take my word for it 😉)

And in production mode we see :

IMDIRECTLYONTHESERVER

When deploying a site with Netlify, environment variables can be set directly from the interface. This is particularly useful for information such as API keys which should be kept secret.

⚠️ Note: it is important to ensure that any secret keys are not visible in a public repository.

Build environment variables

Updated 2024-02-14

Native Environment variables

These are not to be confused with native environment varibales that are available on a unix system

these include:

  • $PATH: system file paths (colon separtated)

It should be noted that these are not the same as the environment variables that are set in the .env file. These are set by the system and are not accessible in the same way.

Environment variables can also be set inlined in a command line. For example:

API_URL=https://my.api.com node code.js

The code in code.js can then access the API_URL variable.

Resources