Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 492
Owl Avatar asked Dec 13 '25 19:12

Owl


1 Answers

I know it's a little bit late, but there is a new way to manage environment variables.

There are 4 types:

  • public
  • private
  • static
  • dynamic

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

like image 154
lsabi Avatar answered Dec 16 '25 20:12

lsabi