Search code examples
environment-variablessveltevitedotenv

How to load environment variables in Svelte using Vite or Svite


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 ??


Solution

  • 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..