Safely accesing server-side only environment variable on SveletKit with Vite

Viewed 270

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
0 Answers
Related