npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

sly-svelte-location-router

v3.3.2

Published

A simple svelte router based on location API

Readme

sly-svelte-location-router

A lightweight and flexible router for Svelte applications with advanced nested routing capabilities, leveraging path-to-regexp for powerful route matching.

Features

  • Nested Routing: Full support for deeply nested router hierarchies
  • Context-based Route Resolution: Efficient segment-by-segment route resolution
  • Fallback Propagation: Error handling that bubbles up through router hierarchy
  • Route Redirects: Simple string-based route redirection
  • Path Parameters: Dynamic route parameters with full TypeScript support
  • Lazy Loading: Automatic code-splitting with dynamic imports
  • Auto-initialization: Routers initialize automatically when mounted
  • TypeScript First: Complete TypeScript support with strict typing
  • Longest Path Matching: Intelligent route sorting prioritizes longer, more specific paths

Installation

pnpm install sly-svelte-location-router

Basic Usage

Automatic Initialization (Recommended)

<script lang="ts">
  import { Router } from 'sly-svelte-location-router';
  import type { Routes } from 'sly-svelte-location-router';

  const routes: Routes = {
    '/': () => import('./routes/Home.svelte'),
    '/about': () => import('./routes/About.svelte'),
    '/users/:id': () => import('./routes/UserDetail.svelte'),
    '/legacy-path': '/about', // Redirect
  };
</script>

<Router {routes} fallback={() => import('./routes/404.svelte')}>
  <div>Loading...</div>
</Router>

Manual Initialization

For advanced use cases where you need precise control over router initialization, you can use initRouter() instead of the Router component:

<script lang="ts">
  import { initRouter, navigate } from 'sly-svelte-location-router';
  import { onMount } from 'svelte';

  onMount(() => {
    // Initialize router manually - handles URL changes and navigation
    initRouter();
    
    // You'll need to implement your own route resolution logic
    // This approach is for advanced users who want full control
  });
</script>

<!-- Custom routing implementation -->
<div>Your custom route rendering logic here</div>

Nested Routing

Create complex nested route structures by using Router components within your route components:

<!-- routes/Admin.svelte -->
<script lang="ts">
  import { Router } from 'sly-svelte-location-router';
  import type { Routes } from 'sly-svelte-location-router';
  
  const routes: Routes = {
    '/': () => import('./admin/Dashboard.svelte'),
    '/users': () => import('./admin/Users.svelte'),
    '/users/:id': () => import('./admin/UserDetail.svelte'),
    '/settings': () => import('./admin/Settings.svelte'),
  };
</script>

<div class="admin-layout">
  <nav><!-- Admin navigation --></nav>
  
  <main>
    <Router {routes} fallback={() => import('./admin/NotFound.svelte')}>
      <div>Loading admin content...</div>
    </Router>
  </main>
</div>

URL Examples:

  • /admin → Admin layout + Dashboard
  • /admin/users → Admin layout + Users list
  • /admin/users/123 → Admin layout + User detail for ID 123
  • /admin/invalid → Admin layout + Admin-specific 404 page

Route Resolution Strategy

The router uses a sophisticated segment-by-segment resolution strategy:

  1. Longest Path First: Routes are sorted by length and specificity
  2. Segment Consumption: Each router consumes matching path segments
  3. Remaining Propagation: Unmatched segments pass to nested routers
  4. Fallback Bubbling: Unresolved routes trigger fallbacks up the hierarchy

Example with /shop/products/123:

Main Router: matches '/shop' → loads Shop component, remaining: ['products', '123']
Shop Router: matches '/products/:id' → loads ProductDetail, remaining: []

Route Definitions

Function Routes (Recommended)

'/users/:id': () => import('./routes/UserDetail.svelte')

Named Routes

'/posts/:category/:id': {
  name: 'post-detail',
  component: () => import('./routes/PostDetail.svelte')
}

Redirects

'/old-users': '/users',           // Simple redirect
'/legacy/:id': '/users/:id'       // Parameter-preserving redirect

Route Guards

Protect routes with async guard functions:

'/admin': {
  name: 'admin',
  component: () => import('./routes/Admin.svelte'),
  guard: async () => {
    const isAuthenticated = await checkAuth();
    if (!isAuthenticated) {
      // Redirect with state
      return {
        path: '/login',
        state: { message: 'Please login to access admin area' }
      };
    }
    return null; // Allow access
  }
}

Route Props

All route components receive a standardized route prop containing route information. The examples use Svelte 5's rune syntax ($props(), $derived) for modern, reactive component development:

interface RouteProps {
  params?: RouteParams      // Route parameters from URL
  error?: ErroneousRouteStore  // Error info for fallback components  
  state?: any              // Navigation state data
  search?: { [key: string]: string }  // Query parameters from URL search string (only for final route)
}

Accessing Route Parameters

<!-- UserDetail.svelte -->
<script lang="ts">
  import type { RouteProps } from 'sly-svelte-location-router';
  
  let { route }: { route: RouteProps } = $props();
  
  // For /users/123, route.params.id === '123'
  const userId = $derived(route.params?.id);
</script>

<h1>User: {userId}</h1>

Supported Parameter Types:

  • :id - Required parameter
  • :id? - Optional parameter
  • :path* - Zero or more segments
  • :path+ - One or more segments

Navigation State

Access state passed during navigation or from guards:

<script lang="ts">
  import type { RouteProps } from 'sly-svelte-location-router';
  
  let { route }: { route: RouteProps } = $props();
  
  // Access state from guard redirects
  const message = $derived(route.state?.message);
</script>

{#if message}
  <div class="alert">{message}</div>
{/if}

Query Parameters

Access URL query parameters in the final route component:

<script lang="ts">
  import type { RouteProps } from 'sly-svelte-location-router';
  
  let { route }: { route: RouteProps } = $props();
  
  // For /products?category=electronics&sort=price
  // route.search = { category: 'electronics', sort: 'price' }
  const category = $derived(route.search?.category);
  const sortBy = $derived(route.search?.sort);
</script>

<h1>Products</h1>
{#if category}
  <p>Filtered by: {category}</p>
{/if}

Note: Query parameters are only available in the final route component, not in intermediate nested routers.

Error Handling in Fallback Components

Fallback components receive error information through the same interface:

<!-- 404.svelte -->
<script lang="ts">
  import type { RouteProps } from 'sly-svelte-location-router';
  
  let { route }: { route: RouteProps } = $props();
  
  const errorPath = $derived(route.error?.path);
</script>

<h1>404 - Not Found</h1>
<p>The path "{errorPath}" could not be found.</p>

Programmatic Navigation

import { navigate } from 'sly-svelte-location-router';

// Navigate to a new route
navigate('/users/123');

// Navigate with state
navigate('/dashboard', { from: 'login', userId: 123 });

// Works with nested routes
navigate('/admin/users/456');

Error Handling & Fallbacks

Fallbacks handle unmatched routes and can be defined at any router level:

<!-- Main app fallback -->
<Router {routes} fallback={() => import('./routes/404.svelte')}>
  <div>Loading...</div>
</Router>

<!-- Admin-specific fallback -->
<Router {adminRoutes} fallback={() => import('./admin/NotFound.svelte')}>
  <div>Loading admin...</div>
</Router>

Fallback Resolution:

  1. Child router tries to match route
  2. If no match, checks for local fallback
  3. If no local fallback, error propagates to parent
  4. Parent router tries its fallback
  5. Process continues up the hierarchy

Advanced Examples

E-commerce Site Structure

/                    → Homepage
/products           → Product list  
/products/123       → Product detail
/cart               → Shopping cart
/admin              → Admin dashboard
/admin/products     → Admin product management
/admin/orders       → Admin order management

Implementation:

<!-- App.svelte -->
<script lang="ts">
  const routes = {
    '/': () => import('./routes/Home.svelte'),
    '/products': () => import('./routes/Products.svelte'),
    '/products/:id': () => import('./routes/ProductDetail.svelte'),
    '/cart': () => import('./routes/Cart.svelte'),
    '/admin': () => import('./routes/Admin.svelte'),
  };
</script>

<Router {routes} fallback={() => import('./routes/404.svelte')}>
  <div>Loading...</div>
</Router>

TypeScript Support

Full TypeScript support with strict typing:

import type { Routes, RouteProps, RouteDefinition } from 'sly-svelte-location-router';

const routes: Routes = {
  '/users/:id': () => import('./UserDetail.svelte')
};

// In your component (Svelte 5)
let { route }: { route: RouteProps } = $props();

// Type-safe access to params
const userId = $derived(route.params?.id);

API Reference

Router Component

  • routes: Routes - Route configuration object
  • fallback?: RouteDefinition - Fallback component for unmatched routes
  • children? - Loading component (rendered during route transitions)

navigate(path: string, state?: any)

Programmatic navigation function with optional state.

initRouter()

Manual router initialization function. Use this instead of the Router component when you need to implement custom route resolution logic. This function sets up URL change listening and navigation event handling, but you'll need to implement your own route matching and component rendering.

currentRoute

Svelte store containing the current route information. Contains path, params, and parentPath for reactive route tracking.

Types

  • Routes - Route configuration object type
  • RouteDefinition - Union type for route definitions
  • RouteProps - Props interface for route components
  • RouteParams - Route parameter object type
  • RouteComponent - Lazy-loaded component type
  • RouteGuard - Guard function type for route protection

License

MIT

Contributing

Contributions welcome! Please feel free to submit a Pull Request.