sv-router

repository·main·Indexed 41 days ago

https://github.com/colinlienard/sv-router

A lightweight (~5kB gzipped), high-performance, type-safe router for Svelte 5 SPAs. Supports both code-based and file-based routing, nested routes, reactive search parameters, and route hooks for guards and data loading. Version 0.19.0.

Tokens
25.2K
Snippets
108
Records
128
Agent score
69%

What's inside sv-router

  1. Overview of sv-router features

    main

    sv-router is a flexible, ergonomic, and complete router designed specifically for Svelte 5. Key features include:

    • Type-safe navigation: Prevents broken links during development.
    • File-based routing (optional): Provides a meta-framework-like developer experience.
    • Lightweight: Small footprint (~5kB gzipped).
    • Performance: Includes built-in code splitting and preloading.
    • Reactive search params: Simplifies state management using URL parameters.
    • Nested routes: Allows sharing layouts across different page levels.
    • Hooks: Supports navigation guards, data loading, and analytics tracking.
    • Hash-based routing: Compatible with environments like Electron or Tauri.
  2. Key features of sv-router

    main

    sv-router is a lightweight (< 5 kB gzipped) router built natively for Svelte 5 using runes. Its core features include:

    • Type-safe navigation: Compile-time validation for paths, parameters, and search params to prevent broken links.
    • Flexible routing modes: Supports both code-based routing (explicitly defined in code) and file-based routing (meta-framework style).
    • Nested layouts: Support for hierarchical route structures.
    • Advanced routing capabilities: Includes hooks for route guards and data loading, preloading strategies, reactive search parameters, and hash-based routing support.
  3. When to use sv-router vs SvelteKit

    main

    Choose sv-router if you are building a Single-Page Application (SPA) and want to avoid the complexity of a full-stack meta-framework. It is ideal for:

    • Dashboards and internal tools where SSR is unnecessary.
    • Desktop apps (Electron/Tauri) using hash-based routing.
    • Decoupled architectures where your backend is separate from your frontend.
    • Svelte 5 projects that require a modern, rune-based router.

    Choose SvelteKit if your project requires:

    • Server-Side Rendering (SSR).
    • Form actions.
    • A full-stack framework experience with integrated server routes.
  4. Choose between Flat or Tree route organization

    main

    You can organize your file-based routes using either Flat Mode or Tree Mode, or a combination of both.

    • Flat Mode: Routes are defined using dot-separated filenames at the root of the routes directory (e.g., about.contact.svelte becomes /about/contact).
    • Tree Mode: Routes are organized in a hierarchical directory structure using index.svelte files to represent the directory path (e.g., about/contact.svelte becomes /about/contact).

    Note: Routes are case-insensitive and trailing slashes are ignored (e.g., /about and /About/ are identical).

    # Flat Mode Example
    routes
    ├── about.svelte                       ➜ /about
    ├── about.contact.svelte               ➜ /about/contact
    ├── about.work.svelte                  ➜ /about/work
    └── about.work.mywork.svelte           ➜ /about/work/mywork
    
    # Tree Mode Example
    routes
    └── about
       ├── contact.svelte                  ➜ /about/contact
       ├── index.svelte                    ➜ /about
       └── work
          ├── index.svelte                 ➜ /about/work
          └── mywork.svelte               ➜ /about/work/mywork
  5. Organize routes using Flat Mode or Tree Mode

    main

    You can organize your route configuration using two different structural patterns:

    1. Flat Mode: All routes are defined at the root level of the configuration object using absolute paths.
    2. Tree Mode: Routes are organized hierarchically. A route key can map to a nested object where keys represent sub-paths relative to the parent.

    You can mix both modes within a single configuration to suit your application's complexity.

    // Flat Mode
    '/about': About,
    '/about/work': Work,
    '/about/work/mywork': MyWork,
    '/about/contact': Contact,
    
    // Tree Mode
    '/about': {
      '/': About,
      '/work': {
        '/': Work,
        '/mywork': MyWork,
      },
      '/contact': Contact,
    },
  6. Manage scroll restoration

    main

    The router uses the browser's native scroll restoration by default, which automatically restores scroll positions when using the back/forward buttons.

    To implement custom scroll restoration logic or to disable the automatic behavior entirely, set the scrollRestoration property of the browser's history object to 'manual'.

    history.scrollRestoration = 'manual';
  7. Understand scroll restoration

    main

    The router uses the browser's native scroll restoration mechanism by default, which automatically restores scroll positions when the user uses the browser's back/forward buttons.

    If you need to implement custom scroll restoration logic or disable the automatic behavior, you must opt-out by setting the scrollRestoration property of the History API to 'manual'.

    history.scrollRestoration = 'manual';
  8. Enable hash-based routing

    main

    To enable hash-based routing, set the base option to '#'. In this mode, the router matches routes using the URL hash instead of the pathname.

    Important considerations:

    • This is useful for applications served via file:// URLs.
    • The hash segment of the URL is reserved exclusively for routing.
    • Any hash property provided in the navigate(path, options?) function will be ignored.
    // Example configuration for hash-based routing
    // In vite.config.ts
    plugins: [router({ base: '#' })]
  9. Use hash-based routing for file:// URLs

    main

    To enable hash-based routing, set the base option to '#'. When this mode is active, the router matches routes using the URL's hash instead of the pathname.

    Important considerations:

    • This is useful for applications served directly from disk via file:// URLs.
    • The hash segment of the URL is reserved exclusively for routing.
    • Any hash property passed in the options object of the navigate(path, options?) function will be ignored.
    export const { p, navigate, isActive, route } = createRouter(
    	{
    		// ...your routes
    	},
    	{ base: '#' },
    );
  10. Organize routes with Route Groups

    main

    In file-based routing, you can group related route files into a folder without including that folder's name in the URL path. To create a route group, prefix the folder name with an underscore (e.g., _folder-name). This is useful for logical organization or for applying shared structures to a subset of routes without affecting the URL hierarchy.

    routes
    ├── index.svelte        ➜ /
    └── _marketing
        ├── about.svelte    ➜ /about
        └── contact.svelte   ➜ /contact
  11. Manage document head with <svelte:head>

    main

    To dynamically update metadata like the page title or meta tags for specific routes in an sv-router application, use Svelte's native <svelte:head> element within your route components.

    <svelte:head>
    	<title>About</title>
    	<meta name="description" content="..." />
    </svelte:head>