| | |

SvelteKit 09 🧡 App State & Environment Variables — Reading $app/state and $env

⏱️ Estimated read: 8 min | |

SvelteKit provides specialized modules to bridge the gap between your application code, the current navigation context, and the host environment. Managing how an application understands its own state—such as current page metadata, ongoing navigations, or version updates—is critical for building responsive, reliable UIs. Simultaneously, handling environment configuration requires a clear distinction between secrets that stay on the server and variables that are safe to leak to the browser.

This chapter details how to use $app/state to monitor navigation lifecycle events, how to distinguish between build-time and runtime environment variables, and how to maintain security boundaries when exposing configuration to the client. We will explore the reactivity of page state and the structural differences between static and dynamic environment imports.

Key point: SvelteKit exposes $app/state for reactive monitoring of navigation and page data on the client, while $env modules provide a secure, type-safe API for accessing environment variables, categorized by visibility (public/private) and timing (static/dynamic).


Why exists

The navigation tracking problem. In a client-side routed application, components often need to know if a navigation is currently in progress to show loading states or to highlight active menu items. $app/state centralizes this, providing a reactive source of truth for the entire application.

The secret leakage risk. Developers often accidentally expose sensitive API keys to the browser. SvelteKit’s $env/static/private modules prevent this by throwing build-time errors if a private variable is imported in a client-side context, enforcing a hard boundary for security.

The build-time vs. runtime trade-off. Some configuration is fixed at build time (e.g., a version number), while other configuration (e.g., a database URL) might change depending on the container or host environment. Static and dynamic imports allow you to choose the performance/flexibility profile that fits each variable.

The consistency challenge. Relying on process.env or platform-specific global objects makes code harder to test and port between adapters. SvelteKit’s modules provide an isomorphic, consistent interface that works locally, in serverless environments, or in static builds.

The cache invalidation problem. Users often keep tabs open for long periods. The updated store in $app/state allows applications to detect if a new version of the site has been deployed, enabling the app to prompt the user to refresh their browser for the latest changes.


a. Managing UI with $app/state

The $app/state module provides three reactive stores: page, navigating, and updated. The page store contains information about the current page, such as url, params, and data. The navigating store is null unless a navigation is in progress, containing the from and to URLs. The updated store is a boolean that triggers if a newer version of the site exists on the server.

// Accessing current navigation state
import { navigating, page } from '$app/state';

// This reactive expression updates automatically
$: isLoading = navigating !== null;
$: currentPath = page.url.pathname;

These stores are fully reactive. When the user navigates, the values inside page update instantly. You can use these in your top-level layout to show global progress bars or breadcrumbs without manually passing state through every component.


b. Static vs. Dynamic environment imports

SvelteKit differentiates environment variables based on when they are resolved. $env/static variables are replaced by their values at build time. They are high-performance and safe for constants. $env/dynamic variables are evaluated at runtime, making them necessary for environments where values are injected after the build is finished (e.g., standard Docker deployments).

// Static: Fast, fixed at build time
import { API_KEY } from '$env/static/private';

// Dynamic: Flexible, evaluated on every request
import { env } from '$env/dynamic/private';
const DATABASE_URL = env.DATABASE_URL;

Public variables are prefixed with PUBLIC_ and can be imported into client-side code. Private variables are stripped from client-side bundles entirely. Always prefer static for keys that don’t change, as it allows the compiler to prune dead code and improve bundle security.


c. Security boundaries and public/private access

The distinction between public and private is enforced by SvelteKit’s module resolver. Importing a private variable in a file that runs on the client will cause a build error. This is a deliberate design choice that prevents developers from accidentally bundling server-side secrets in client JavaScript.

// Safe for server-side files only (+page.server.ts)
import { SECRET_KEY } from '$env/static/private';

// Safe for any file, including client-side (+page.svelte)
import { PUBLIC_API_URL } from '$env/static/public';

When building for different targets, SvelteKit ensures that public variables are serialized into the HTML output, while private variables are strictly ignored. This allows your client code to remain “environment-aware” without having visibility into sensitive server configurations.


Complete Example Session

// ============================================
// PART 1: TRACKING NAVIGATION
// ============================================
import { navigating } from '$app/state';
// UI shows loading bar if navigating exists
$: isNavigating = navigating !== null;

// ============================================
// PART 2: STATIC PRIVATE ENV
// ============================================
// src/routes/+page.server.ts
import { AUTH_TOKEN } from '$env/static/private';
// Used for server-to-server auth

// ============================================
// PART 3: DYNAMIC PUBLIC ENV
// ============================================
// src/routes/config/+server.ts
import { env } from '$env/dynamic/public';
// Useful for runtime-injected hosts

// ============================================
// PART 4: DETECTING UPDATES
// ============================================
import { updated } from '$app/state';
// Trigger refresh prompt if updated.current is true

// ============================================
// PART 5: PAGE METADATA
// ============================================
import { page } from '$app/state';
// Reactive page.params for routing logic

// ============================================
// PART 6: TYPE SAFETY
// ============================================
// SvelteKit automatically generates types for .env
// No need for 'any' types on env variables

// ============================================
// PART 7: PUBLIC STATIC
// ============================================
import { PUBLIC_THEME } from '$env/static/public';
// Theme persists across server/client

// ============================================
// PART 8: DYNAMIC PRIVATE
// ============================================
import { env as dynamicEnv } from '$env/dynamic/private';
// Used for variable hostnames

// ============================================
// PART 9: NAVIGATION CANCELLATION
// ============================================
// Logic in +layout.svelte based on 'navigating'

// ============================================
// PART 10: CONFIGURATION BRIDGE
// ============================================
// Passing public env to external JS libs safely

This sequence covers the use of stores for UI feedback, the correct selection of static/dynamic loaders, and the enforcement of security through variable scoping.


Quick Reference

App State Modules

VariableTypePurpose
pageStoreCurrent URL, params, data
navigatingStoreCurrent nav status, from/to
updatedStoreTrue if new build available

Environment Modules

Import PathVisibilityResolution
$env/static/publicPublicBuild-time
$env/static/privatePrivateBuild-time
$env/dynamic/publicPublicRuntime
$env/dynamic/privatePrivateRuntime

Best Practices

✅ Do This:

// Use static for fixed config
import { API_KEY } from '$env/static/private';             // ✅

// Use navigating store for global progress
$: loading = navigating !== null;                          // ✅

// Use dynamic for runtime-configured hosts
import { env } from '$env/dynamic/private';                // ✅

// Keep public variables prefixed
PUBLIC_API_URL=https://api.example.com                     // ✅

❌ Don’t Do This:

// Do not import private keys in .svelte files
import { SECRET } from '$env/static/private';              // ❌

// Do not use process.env directly
const key = process.env.KEY;                               // ❌

// Do not assume static variables change
// (They are baked at build time)                          // ❌

Common Pitfalls

PitfallWhy It HappensFix
Secret LeakImporting private in clientMove to +page.server.ts
Stale ConfigUsing static for host-specific envsSwitch to dynamic
Type ErrorsMissing .env declarationsRun npm run dev to generate
Nav flickeringnavigating check issuesWrap in {#if navigating}

Real-World Examples

1. Global Loading State

import { navigating } from '$app/state';

2. Accessing Page Parameters

import { page } from '$app/state';

3. Reading Static Secret

import { API_KEY } from '$env/static/private';

4. Dynamic Host Detection

import { env } from '$env/dynamic/private';

5. Public URL for components

import { PUBLIC_CDN } from '$env/static/public';

6. Version Update Notification

import { updated } from '$app/state';

7. Server-side API Proxy

import { PROXY_TARGET } from '$env/static/private';

8. Conditional Runtime Config

const { HOST } = env;

9. Responsive Nav Logic

if (navigating?.to?.url.pathname === '/admin') { ... }

10. Type-safe Envs

// $env/static/private.d.ts auto-generated

Visual

Reactivity Boundary

┌──────────────────────────────────────────────┐
│  $app/state (Stores)                         │
│  page       ──► current URL/data             │
│  navigating ──► loading status               │
│  updated    ──► deployment notification      │
│      │                                       │
│      ▼                                       │
│  Svelte Components (Reactive UI)             │
└──────────────────────────────────────────────┘

Environment Scoping

┌──────────────────────────────────────────────┐
│  PRIVATE (Server-side)                       │
│  ┌───────────────────────┐                   │
│  │ Stays in build/server │                   │
│  └───────────────────────┘                   │
│      ▲                                       │
│  PUBLIC (Client-side)                        │
│  ┌───────────────────────┐                   │
│  │ Bundled in JS/HTML    │                   │
│  └───────────────────────┘                   │
└──────────────────────────────────────────────┘

Static vs Dynamic Timing

┌──────────────────────────────────────────────┐
│  STATIC ──► Resolved at Build Time           │
│  (Fastest, secure constants)                 │
│                                              │
│  DYNAMIC ──► Resolved at Runtime             │
│  (Configured per environment/container)      │
└──────────────────────────────────────────────┘

Summary

ItemValue
$app/stateNavigation and page stores
navigatingDetects transition status
updatedDetects new deployments
staticBuild-time env variables
dynamicRuntime env variables
PublicExposed to client
PrivateServer-only access

Key takeaways:

  • Use $app/state for reactivity. The page and navigating stores are the primary tools for building navigation-aware UI components.
  • Respect the visibility boundary. Never import from private folders in files that end up in the client bundle; the SvelteKit build process will stop you.
  • Choose the right timing. Use static for keys known at development/CI time and dynamic for configuration that only exists inside a production Docker container or cloud environment.
  • Prefix public variables. Always use the PUBLIC_ prefix for any environment variable you intend to consume in your Svelte components.
  • Benefit from type safety. SvelteKit generates TypeScript definitions for your environment variables based on your .env file, reducing runtime errors.

Remember: Mastering environment and application state is about managing trust and visibility. By using $app/state to drive your UI’s responsiveness and $env modules to tightly control what information leaks into your client-side bundles, you create a robust, secure, and maintainable application that adapts gracefully to different deployment scenarios.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!