I recently learned a nice way to manage your .env files in your Svelte projects. If you're using Rollup as your bundling tool, which is likely to be the case, you can use the node module dotenv to automatically inject the content of a .env file into your web page.

  1. Install dotenv via npm install dotenv

  2. At the top of your rollup.config.js, import and load the environment variables:
import dotenv from "dotenv"
dotenv.config() // inject the content of the .env file into 'process.env'
  1. Then, in the plugins section, if you're already using svelte-preprocess, modify the following:
    plugins: [
            // ...
            preprocess: sveltePreprocess({
                // 👇 Add this attribute
                replace: [["process.env.MY_ENV_VAR", process.env.MY_ENV_VAR]],

And that's it. Now anywhere in your Svelte component and related Javascript (or Typescript) code you should be able to reference process.env.MY_ENV_VAR.