By Ivan Santos - Thu Jul 14 2022

Add Environment Variable to SvelteKit

This post will go over how to load environment variables in a SvelteKit application.

SvelteKit uses Vite under the hood for bundling your webapp, and Vite has:

  • .env package preconfigured. For those, who don’t know .env comes is the standard way for securing environment variables.
  • exposes all variables to the client that starts with VITE_.

With this knowledge. This makes it super easy for you to load environment variables in your app.

All you need to do is create file: .env on the root of your sveltekit app, and create a env variable prefixed with VITE_.

Create env var locally

VITE_TEST_VAR='hello world'

Then in any of your svelte file, you can easily import env var by adding import.meta.VITE_TEST_VAR.

<script lang="ts">
	let envVar = import.meta.env.VITE_TEST_VAR;

NOTE: Keep in mind, that if you use the variables on the client side, it can be leaked. Just make sure that your secret variables are only used in used in the SvelteKit endpoints.

Add type to your env var

If you are using typescript, vite also gives typescript intellisense support out-of-the-box for your VITE env variables. All you need to do is to create env.d.ts to the src/ directory.

interface ImportMetaEnv {
  readonly VITE_TEST_VAR: string

interface ImportMeta {
  readonly env: ImportMetaEnv

Your final project structure should look like this:

├── .env <---
├── package-lock.json
├── package.json
├── src
│   ├── app.d.ts
│   ├── app.html
│   ├── env.d.ts <---
│   └── routes
│       └── index.svelte
├── static
│   └── favicon.png
├── svelte.config.js
└── tsconfig.json

External Links: