I have 2 environment variables on my SvelteKit app for my API endpoint, one is public API, one is internal API (accessing API directly via IP to bypass Cloudflare, etc.)
This is what I roughly want:
API_URL = runningInBrowser ? "https://example.com/api" : "https://101.101.101.101/api"
How can I safely put both of my environment variables and make sure that the internal API isn't exposed on client side / from SvelteKit's server-side renderer? I couldn't find a clear way to do it on Vite's doc.
What I'm planning to do is checking if the code is running on server side or not, if it's running on server side, access server side env variable using dotenv and process.env, otherwise use Vite's env variable. Is this method safe?
import { browser } from "$app/env";
if (!browser) dotenv.config(); // load .env if on server-side
const API_URL = browser ?
import.meta.env.VITE_API_URL : // access exposed environment variable by Vite
process.env.API_BASe_URL // access server side variable
I know it's a little bit late, but there is a new way to manage environment variables.
There are 4 types:
private variables are only for server side code, while public are meant to be used for client code.
static variables are to be used at build time, while dynamic ones are meant to be used dynamically.
They can be accessed like
import { env } from "$env/dynamic/public";
import { env } from "$env/static/public";
import { env } from "$env/dynamic/private";
import { env } from "$env/static/private";
Beware that the private modules can only be accessed server side.
See https://kit.svelte.dev/docs/modules#$env-dynamic-private for more information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With