How to load environment variables in Svelte using Vite or Svite

Viewed 6092

I've been trying to figure out best practices on implementing environment variables for API configurations in Svelte App. As far as I know, We have to use either Vite or Svite to make it work. Can anyone help me find a solution please ??

3 Answers

This is how I did it but I bet there are other good practices

I make use of dotenv and $lib provided by SvelteKit.

Below are my folder structure and related js:

├── sveltekit-project/        // Root
|   ├── src/
|   |   ├── lib/
|   |   |   ├── env.js
|   |   |   ├── other.js
|   |   |   ... 
|   |   |   
|   |   ├── routes/
|   |   |   ├── main.svelte
|   |   |   ...
|   |   ├── app.html
|   |   ...
|   ├── .env
/** /src/lib/env.js **/
import dotenv from 'dotenv'

dotenv.config()

export const env = process.env
/** /src/lib/other.js **/
import { env } from '$lib/env'

const secret = env.YOUR_SECRET

By the way, I recommend you reading the "How do I use environment variables?" part in SvelteKit FAQ. It seems very relevant to what you concern, but I am afraid it means some workarounds are needed instead of the VITE_* variables..

  1. Make sure all your environment variables start with the prefix "VITE_".

Example:

VITE_API_KEY=8465313163463435434353535
  1. Include your variable in the Svelte file using the syntax "import.meta.env.VARIABLE_NAME".

Example:

headers: {
          "X-RapidAPI-Key": import.meta.env.VITE_API_KEY
        }

And that's it. Hope that helps.

Warning

The VITE_ prefix would expose sensitive information to client side! More info

Normally, I'd simply delete this answer, but its clear that the whole import.meta.env.VITE_SECRET_PASSWORD is not a clever design. What is the point of using a .env variable that is not secure, per the security note warning at https://vitejs.dev/guide/env-and-mode.html#env-files ??

As a developer, my expectation is that I can use .env variables to store secure information.

Let this answer stand as a warning: Do not do this.

My original response below:

I spent some time struggling here..

Environment Variable file, must be named .env:

VITE_SENDGRID_API_KEY=SG.9999999999....999999999999

I spent way too much time to figure out that sendgrid.env as a filename will not work.

I added a file to the /src/lib directory called env.js. Here are the complete contents of that file:

export const ENV_OBJ = {
    SENDGRID_API_KEY: import.meta.env.VITE_SENDGRID_API_KEY,
    TEST: "test, test, test"
};

And then when I need it elsewhere...

import { ENV_OBJ } from '$lib/env'
// console.log("API Key.test: ", ENV_OBJ.TEST);
sgMail.setApiKey(ENV_OBJ.SENDGRID_API_KEY);

I'm using SvelteKit, Javascript, etc... No extra dotenv. Keep it simple, make it easy.

Related