Keep secrets in .env, expose safe values with the PUBLIC_ prefix, and read them through SvelteKit’s typed $env modules.
Why: keep secrets (database URLs, API keys) out of your code and in a .env file, which is git-ignored. SvelteKit reads it for you. Note: variables you want in the browser MUST start with PUBLIC_.
# .env (do not commit this file)
DATABASE_URL=postgres://localhost:5432/app
PUBLIC_SITE_URL=https://example.comWhy: import secrets from $env/static/private. SvelteKit guarantees this module can never be imported into client code, so the value stays on the server.
// src/lib/server/db.ts
import { DATABASE_URL } from '$env/static/private'
export const db = connect(DATABASE_URL) // safe — server onlyWhy: values that are safe to expose (and prefixed PUBLIC_) come from $env/static/public, and you can use them anywhere, including in components that run in the browser.
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { PUBLIC_SITE_URL } from '$env/static/public'
</script>
<a href={PUBLIC_SITE_URL}>Home</a>Why: $env/static/* values are baked in at build time (fastest). If a value is only known when the server starts (set by your host), read it from $env/dynamic/private or /public instead, via the env object.
// Read at runtime instead of build time
import { env } from '$env/dynamic/private'
const key = env.SECRET_API_KEY // resolved when the server runs