| | |

Svelte 70 🧡 Managing App State with SvelteKit Stores ($page, $navigating, $updated)

⏱️ Estimated read: 8 min | |

SvelteKit provides a set of specialized stores within the $app/stores module that act as the interface between the framework’s routing engine and your application’s UI. These stores are reactive, meaning components automatically re-render whenever the routing state changes. Instead of relying on brittle manual URL parsing or complex global state management libraries, SvelteKit exposes the internal state of the application directly to your templates through standard Svelte store syntax.

The three primary stores are $page, which contains metadata about the current route; $navigating, which tracks active transitions; and $updated, which monitors for new application deployments. By tapping into these stores, you can build sophisticated UI patterns—such as loading bars, active navigation states, and “new version available” prompts—with minimal boilerplate and maximum performance.

Key point: The built-in stores ($page, $navigating, $updated) provide reactive, synchronized access to SvelteKit’s internal routing and deployment metadata, allowing components to respond dynamically to navigation events and application updates without extra configuration.


Why exists

The reactive routing problem. Manually listening to browser history changes to determine the current URL, route parameters, or page data is prone to bugs and race conditions. $page exists to provide a centralized, consistent source of truth for all current page metadata.

The navigation feedback problem. In a single-page application, users need visual cues during route transitions to know that the app is “working.” $navigating exists to expose whether a transition is pending, enabling the easy implementation of loading spinners, progress bars, or state-based UI disabling.

The stale deployment problem. If a user keeps a tab open for days, they might be running an outdated version of your application while newer assets are live on the server. $updated provides a standardized way to detect this drift and prompt the user to reload the page to catch up with the latest version.

The dependency decoupling problem. Components often need to change behavior based on the current URL path or search parameters. Instead of passing these as props through every layer of the layout, $page allows any component to access them anywhere in the tree.

The framework integration requirement. SvelteKit manages its own internal router state. Exposing this via stores allows the framework to maintain deep integration with Svelte’s reactivity system, ensuring that changes in the URL trigger updates in the exact components that need them, and nothing else.


a. The $page store: The heart of the route state

The $page store contains the most essential information about the current page, including the url (the full URL object), params (dynamic route values), route (the route ID), and data (the results of your load functions). It is accessed as $page in templates or via get(page) in logic blocks.

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

// Reactively log the current route ID
$: console.log("Current route:", $page.route.id);

// Access route params
$: userId = $page.params.id;

The $page.data property is particularly powerful. It contains all the data returned from your load functions, merged across all parent layouts. By accessing $page.data, you can consume global state (like user permissions) in any deeply nested component without prop-drilling from the root layout.


b. The $navigating store: Managing transition feedback

The $navigating store is null when the application is idle. When a user clicks a link that triggers a navigation, $navigating becomes an object containing information about the transition, including the from and to navigation objects. It returns to null once the navigation completes.

<script>
  import { navigating } from '$app/stores';
</script>

{#if $navigating}
  <div class="progress-bar">Loading next page...</div>
{/if}

This store is the standard way to implement global loading indicators. Because it is reactive, the UI automatically updates the moment a navigation starts. This pattern is essential for creating high-quality user experiences where the application feels responsive even when fetching data over slow network connections.


c. The $updated store: Detecting deployment drift

The $updated store tracks whether the version of the application running in the browser is the same as the version currently live on the server. It uses a small, lightweight periodic check. If the versions differ, the store value becomes true, enabling you to display a “Update Available” notification.

<script>
  import { updated } from '$app/stores';
</script>

{#if $updated}
  <button on:click={() => location.reload()}>
    A new version is available! Refresh now.
  </button>
{/if}

This store is inactive by default in terms of heavy polling. SvelteKit handles the version check logic internally. By using $updated, you ensure your users are always on the latest code path, which is critical for apps that rely on hot-fixes or rapid iteration cycles.


Complete Example Session

// ============================================
// PART 1: USING $PAGE FOR DYNAMIC UI
// ============================================
import { page } from '$app/stores';

$: isHome = $page.url.pathname === '/';
$: isAdmin = $page.data.user?.role === 'admin';

// ============================================
// PART 2: LOADING INDICATOR VIA $NAVIGATING
// ============================================
import { navigating } from '$app/stores';

$: isLoading = !!$navigating;

// ============================================
// PART 3: FORCED REFRESH VIA $UPDATED
// ============================================
import { updated } from '$app/stores';

function refresh() {
  if ($updated) location.reload();
}

// ============================================
// PART 4: ACCESSING PARAMS AND QUERY
// ============================================
// Assuming URL is /search?q=svelte
$: searchTerm = $page.url.searchParams.get('q');
$: productId = $page.params.id;

// ============================================
// PART 5: THE UNIFIED LAYOUT EXAMPLE
// ============================================
// In +layout.svelte
<script>
  import { page, navigating, updated } from '$app/stores';
</script>

{#if $navigating} <Spinner /> {/if}
{#if $updated} <UpdatePrompt /> {/if}
<main>
  <h1>Viewing: {$page.url.pathname}</h1>
  <slot />
</main>

These parts show how to combine the three stores to create a responsive, robust layout that handles page data, transition loading, and version updates gracefully.


Quick Reference

The Stores

StoreValue TypePurpose
$pageObjectCurrent route, URL, data
$navigatingObject | nullTracking page transitions
$updatedBooleanDeployment version check

$page Metadata

KeyDescription
urlURL object (origin, pathname)
paramsDynamic route parameters
routeRoute ID
dataMerged load function output

Best Practices

✅ Do This:

// Use $page.data for global auth state
$: user = $page.data.user;                                    // ✅

// Use $navigating for global spinners
{#if $navigating} <Loading /> {/if}                           // ✅

// Always check $updated before taking action
if ($updated) { /* reload */ }                                // ✅

❌ Don’t Do This:

// Don't modify the store objects
$page.data = {};                                              // ❌

// Don't rely on global document.location
$: path = document.location.pathname;                         // ❌

// Don't over-use $navigating for tiny animations
// (can cause layout flickering)                              // ❌

Common Pitfalls

PitfallWhy It HappensFix
Incorrect URL parsingUsing window.locationUse $page.url
Store not updatedOutside reactive scopeUse $ prefix in Svelte
Navigation flicker$navigating triggers too oftenAdd a small setTimeout buffer
Missing data$page.data is incompleteEnsure load returns correct keys

Real-World Examples

1. Conditional CSS Class

<nav class:active={$page.url.pathname === '/admin'}>

2. Search Result Title

<h1>Search results for: {$page.url.searchParams.get('q')}</h1>

3. Global Loading Bar

{#if $navigating} <ProgressBar /> {/if}

4. New Version Warning

{#if $updated} <button on:click={reload}>Update</button> {/if}

5. Admin Panel Logic

$: canEdit = $page.data.user.role === 'editor';

6. Dynamic Page Breadcrumbs

{#each $page.url.pathname.split('/') as segment} {segment} {/each}

7. Tracking Page Views

$: trackPageView($page.url.pathname);

8. Storing Referrer

$: referrer = $page.url.searchParams.get('ref');

9. Route-Based Theme

<div class:dark-mode={$page.route.id.includes('admin')}>

10. Pre-loading State

$: isTransitioning = !!$navigating;

Visual

The Page Lifecycle Store

┌─────────────────────────────────────────────────────────┐
│  Browser Navigation Request                             │
│  │                                                      │
│  ▼                                                      │
│  $navigating (starts) ──► UI: Show Loading State        │
│  │                                                      │
│  ▼                                                      │
│  $page (updates) ──► URL, Params, and Data update       │
│  │                                                      │
│  ▼                                                      │
│  $navigating (null) ──► UI: Remove Loading State        │
└─────────────────────────────────────────────────────────┘

Deployment Check

┌─────────────────────────────────────────────────────────┐
│  Periodic Background Check                              │
│  │                                                      │
│  ▼                                                      │
│  Server Check (manifest.json check)                     │
│  │                                                      │
│  ▼                                                      │
│  $updated ──► (false) ──► (true)                        │
│  │                                                      │
│  ▼                                                      │
│  UI: Show "Update Available" Prompt                     │
└─────────────────────────────────────────────────────────┘

Reactive Store Hierarchy

┌─────────────────────────────────────────────────────────┐
│  STORE INPUTS                                           │
│  ┌───────────┐    ┌─────────────┐    ┌─────────────┐    │
│  │  $page    │    │ $navigating │    │  $updated   │    │
│  └─────┬─────┘    └──────┬──────┘    └──────┬──────┘    │
│        │                 │                  │           │
│        ▼                 ▼                  ▼           │
│  ┌───────────────────────────────────────────────────┐  │
│  │  COMPONENT REACTIVITY (Svelte DOM Updates)        │  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Store Prefix$
$pageCurrent state metadata
$navigatingNavigation status
$updatedDeployment version check
Accessimport from $app/stores

Key takeaways:

  • The $ prefix is mandatory. It signals to the Svelte compiler that you want to subscribe to the store and re-render the component when the value changes.
  • $page is your data hub. Use it to read current URL parameters, query strings, and data fetched by your server-side load functions.
  • $navigating improves UX. It provides the reactive state necessary to implement high-quality loading UI during navigation transitions.
  • $updated ensures reliability. By tracking version drifts, you can maintain a consistent user experience even when the application is updated in the background.
  • Stay reactive. These stores are designed to be consumed directly in the template. Avoid calling get() on them inside event handlers unless you absolutely need a snapshot of the value.

Remember: These stores are the primary window into the framework’s internal routing state. By using them, you keep your components in sync with the current URL and deployment status without writing complex listener code. Treat $page, $navigating, and $updated as the building blocks for creating a smooth, responsive, and robust navigation experience in every SvelteKit application.

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!