svelte-router Svelte Themes

Svelte Router

A client-side SPA router for Svelte 5

@teleology/svelte-router

Tested against Svelte 5.1.3. This is a library for SPA's and does not support SSR at this time.

API

Router Usage

<script lang="ts">
  import { Router } from "@teleology/svelte-router"

  import { Test } from "./routes/Test.svelte"

  let isAuthenticated = true;

  const routes = [
    {
      path: "*",
      // lazy loaded
      component: () => import("./lib/routes/NotFound.svelte"),
    },
    {
      path: "/test"
      // non-lazy load
      component: Test,
    },
    {
      path: "/user",
      component: () => import("./lib/routes/UserProfile.svelte"),
      layout: () => import("./lib/pages/UserLayout.svelte"),
      redirect: "/",
      guard: () => isAuthenticated
    }
  ]
</script>

<Router {routes}>

RouteDefinition

Key Type Description
path String A pathing string
component
  • SvleteComponent
  • () => Promise(SvelteComponent)
An imported SvelteComponent or a lazy-loaded component
layout
  • SvleteComponent
  • () => Promise(SvelteComponent)
An imported SvelteComponent or a lazy-loaded component. Must have {@render children}!!
redirect String An alternate url if the guard function is not true
guard () => Boolean A synchronous function that returns whether the route should be navigated to

Route Usage

<script lang="ts">
  import { push, type RouteDetails } from "@teleology/svelte-router";

  interface Props {
    route: RouteDetails;
  }

  let { route }: Props = $props();
</script>

<h1>You landed on {route.pathname}</h1>

RouteDetails

Route details are extends from the browser Location object

Key Type Description
params Object The key-value object of url params
search Object The key-value object of search params

Utils

  • push(url: string, state?: any)
  • replace(url: string, state?: any)
  • back()

Top categories

Loading Svelte Themes