### Start sv-router Dev Server
Source: https://github.com/colinlienard/sv-router/blob/main/create/templates/file-based-js/README.md
Use this command to start the development server for your sv-router project.
```bash
npm run dev
```
--------------------------------
### Create New sv-router Project
Source: https://github.com/colinlienard/sv-router/blob/main/README.md
Use this command to start a new project with sv-router.
```bash
npm create sv-router
```
--------------------------------
### Flat Route Organization Example
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-definition.md
Demonstrates a flat directory structure for defining routes. Each file directly maps to a route path.
```bash
routes
├── about.svelte ➜ /about
├── about.contact.svelte ➜ /about/contact
├── about.work.svelte ➜ /about/work
└── about.work.mywork.svelte ➜ /about/work/mywork
```
--------------------------------
### Install sv-router in Existing Project
Source: https://github.com/colinlienard/sv-router/blob/main/README.md
Add sv-router to an existing project using npm.
```bash
npm install sv-router
```
--------------------------------
### Testing Setup
Source: https://github.com/colinlienard/sv-router/blob/main/AGENTS.md
Configuration for Vitest testing framework, including happy-dom environment and common testing libraries like @testing-library/svelte.
```javascript
// tests/vitest-setup.js
import '@testing-library/jest-dom'
import { vi } from 'vitest'
// Mock browser APIs if needed
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation(query => ({
matches: false,
})),
});
```
--------------------------------
### Run Documentation Site Locally
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Start a local development server for the VitePress documentation site using `pnpm docs:dev`. This allows for real-time previewing of documentation changes.
```bash
pnpm docs:dev
```
--------------------------------
### Dynamic Route Filename Examples
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/dynamic-routes.md
Demonstrates how to structure filenames for dynamic routes in both flat and tree modes. Use square brackets to denote dynamic segments.
```sh
routes
├── user.[id].svelte ➜ /user/123
└── user.[id].post.[postId].svelte ➜ /user/123/post/456
```
```sh
routes
└── user
└── [id]
├── index.svelte ➜ /user/123
└── post
└── [postId].svelte ➜ /user/123/post/456
```
--------------------------------
### Add Postinstall Script for Route Generation
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/manual-setup.md
Ensure routes are generated automatically after installation by adding a postinstall script to package.json.
```json
{
"scripts": {
"postinstall": "sv-router" // [!code ++]
}
}
```
--------------------------------
### Tree Route Organization Example
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-definition.md
Illustrates a tree-like directory structure for organizing routes hierarchically. The index.svelte file defines the root of a directory route.
```bash
routes
└── about
├── contact.svelte ➜ /about/contact
├── index.svelte ➜ /about
└── work
├── index.svelte ➜ /about/work
└── mywork.svelte ➜ /about/work/mywork
```
--------------------------------
### Install sv-router on Existing Project
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/getting-started.md
Add sv-router to an existing Svelte 5 project using your preferred package manager. Ensure Svelte 5 is installed.
```sh
npm install sv-router
```
```sh
pnpm add sv-router
```
```sh
yarn add sv-router
```
```sh
bun add sv-router
```
```sh
deno add npm:sv-router
```
--------------------------------
### Route Group with Layout, Hooks, and Meta
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-groups.md
This example shows a route group containing a layout, hooks, and meta files. The `layout.svelte` file is shared across child routes within the group.
```bash
routes
└── _dashboard
├── layout.svelte
├── hooks.ts
├── meta.ts
└── index.svelte
```
--------------------------------
### File-Based Routing Setup with Vite Plugin
Source: https://context7.com/colinlienard/sv-router/llms.txt
Configure the Vite plugin for file-based routing. This setup automatically generates route mappings from your file structure and supports options like lazy loading and file exclusion.
```typescript
// vite.config.ts
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';
import { router } from 'sv-router/vite-plugin';
export default defineConfig({
plugins: [
svelte(),
router({
path: 'src/routes', // default, can be changed (e.g. 'src/pages')
allLazy: true, // make every route lazy-loaded by default
ignore: [/[A-Z].*\.svelte$/], // exclude non-route component files
js: false, // set true to emit .js instead of .ts
}),
],
});
```
--------------------------------
### Configure CLI with Path
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/configuration.md
Configure the CLI by passing options directly to the `sv-router` command in your `package.json` scripts. This example sets the `path` option to 'src/pages'. CLI arguments override Vite config options.
```json
{
"scripts": {
"postinstall": "sv-router --path src/pages"
}
}
```
--------------------------------
### Code-Based Routing Setup with createRouter
Source: https://context7.com/colinlienard/sv-router/llms.txt
Initialize the router with a static route configuration object. This approach allows for manual definition of routes, including nested structures, lazy loading, and route hooks.
```typescript
// src/router.ts
import { createRouter } from 'sv-router';
import Home from './routes/Home.svelte';
import About from './routes/About.svelte';
import Dashboard from './routes/Dashboard.svelte';
import Settings from './routes/Settings.svelte';
import NotFound from './routes/NotFound.svelte';
export const { p, navigate, isActive, preload, route } = createRouter({
// Flat route
'/': Home,
// Tree route with nested children and a layout
'/about': {
'/': About,
'/team': () => import('./routes/Team.svelte'), // lazy-loaded
},
// Nested tree with layout, hooks, and meta
'/dashboard': {
'/': Dashboard,
'/settings': Settings,
layout: () => import('./routes/DashboardLayout.svelte'),
hooks: {
async beforeLoad({ pathname }) {
const user = await fetchCurrentUser();
if (!user) throw navigate('/login');
},
},
meta: { requiresAuth: true },
},
// Dynamic segment
'/post/:slug': () => import('./routes/Post.svelte'),
// Catch-all (named to expose unmatched segment)
'*notfound': NotFound,
});
```
--------------------------------
### Basic Route Grouping
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-groups.md
Folders prefixed with an underscore are ignored in the URL. This example shows how `_marketing` is excluded, making `about.svelte` and `contact.svelte` available at the root level.
```bash
routes
├── index.svelte ➜ /
└── _marketing
├── about.svelte ➜ /about
└── contact.svelte ➜ /contact
```
--------------------------------
### Ignore Files in CLI
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/configuration.md
Configure the `ignore` option for the CLI using a JSON string representation of a regular expression. This example ignores Svelte files starting with a capital letter.
```json
"postinstall": "sv-router --ignore '[A-Z].*\.svelte$தியான'" // You can have multiple ones separated by commas
```
--------------------------------
### Route Hooks: beforeLoad Example
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Implement route guards and data loading logic using `beforeLoad` hooks. These asynchronous hooks run in order from the root to the leaf route and can trigger redirects by throwing `Navigation`.
```javascript
throw new Navigation('/redirect')
```
--------------------------------
### Define Routes with Metadata and Hooks
Source: https://context7.com/colinlienard/sv-router/llms.txt
Create a router instance defining routes with metadata and hooks. Parent metadata is deep-merged into child routes. The example shows authentication logic in a beforeLoad hook.
```typescript
export const { p, navigate, isActive, route } = createRouter({
'/': { '/': Home, meta: { section: 'public', title: 'Home' } },
'/dashboard': {
'/': Dashboard,
meta: { requiresAuth: true, section: 'app' },
hooks: {
beforeLoad({ meta }) {
if (meta.requiresAuth && !getSession()) throw navigate('/login');
},
},
'/settings': {
'/': Settings,
meta: { title: 'Settings' },
// Resolved meta: { requiresAuth: true, section: 'app', title: 'Settings' }
},
},
});
```
--------------------------------
### Svelte Layout Component Implementation
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/layouts.md
This is an example of a Svelte component that serves as a layout. It receives children and renders them within a wrapper div.
```svelte
{@render children()}
```
--------------------------------
### Define Route Metadata
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-metadata.md
Use a `meta.ts` file to export route metadata. This example sets the `public` property to `false` for the route.
```typescript
import type { RouteMeta } from 'sv-router';
export default {
public: false,
} satisfies RouteMeta;
```
--------------------------------
### Route Group with Layout
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-groups.md
A `layout.svelte` file within a route group wraps all its child routes. This example demonstrates how `layout.svelte` in `_dashboard` applies to `/` and `/settings`, while `/about` remains unwrapped.
```bash
routes
├── about.svelte ➜ /about
└── _dashboard
├── layout.svelte
├── index.svelte ➜ /
└── settings.svelte ➜ /settings
```
--------------------------------
### Configure Vite Plugin with Path
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/configuration.md
Configure the Vite plugin by passing an options object to the `router()` function in your Vite configuration. This example sets the `path` option to 'src/pages'.
```typescript
import { router } from 'sv-router/vite-plugin';
export default defineConfig({
plugins: [
svelte(),
router({
path: 'src/pages',
}),
],
});
```
--------------------------------
### Preload Link on Hover
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/preloading.md
Add the `data-preload` attribute to a link to enable preloading. The component for the linked route will start loading in the background when the user hovers over the link.
```svelte
About
```
--------------------------------
### Add sv-router to Existing Project
Source: https://context7.com/colinlienard/sv-router/llms.txt
Install sv-router as a dependency in an existing Svelte 5 project. This command adds the necessary package to your project's dependencies.
```sh
npm install sv-router
# or
pnpm add sv-router
```
--------------------------------
### Ignore Files with RegExp
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/configuration.md
Use the `ignore` option with an array of regular expressions to exclude files from route generation. This example ignores Svelte files starting with a capital letter.
```typescript
router({ ignore: [/[A-Z].*\.svelte$/] )}
```
--------------------------------
### Create SV Router with Deno
Source: https://github.com/colinlienard/sv-router/blob/main/create/README.md
Use this command to create a new SV Router project with Deno.
```bash
deno run -A npm:create-sv-router@latest
```
--------------------------------
### Build Documentation Site
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Generate a static build of the VitePress documentation site by running `pnpm docs:build`. The output will be in the `docs/dist` directory.
```bash
pnpm docs:build
```
--------------------------------
### Build create-sv-router CLI
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Compile the `create-sv-router` scaffolding CLI for distribution by running `pnpm create:build`. This command prepares the CLI for packaging.
```bash
pnpm create:build
```
--------------------------------
### Run create-sv-router CLI Locally
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Execute the `create-sv-router` scaffolding CLI locally for development purposes using `pnpm create:dev`. This is useful for testing CLI changes.
```bash
pnpm create:dev
```
--------------------------------
### Preventing Navigation
Source: https://github.com/colinlienard/sv-router/blob/main/AGENTS.md
Use `blockNavigation()` to prevent route changes, for example, when a user has unsaved changes. A callback function determines if navigation should be blocked.
```javascript
const { blockNavigation } = createRouter({});
blockNavigation(() => {
// return true to block navigation
return confirm('You have unsaved changes. Are you sure you want to leave?');
});
```
--------------------------------
### Create SV Router with Bun
Source: https://github.com/colinlienard/sv-router/blob/main/create/README.md
Use this command to create a new SV Router project with Bun.
```bash
bun create sv-router
```
--------------------------------
### Create SV Router with NPM
Source: https://github.com/colinlienard/sv-router/blob/main/create/README.md
Use this command to create a new SV Router project with npm.
```bash
npm create sv-router@latest
```
--------------------------------
### createRouter
Source: https://github.com/colinlienard/sv-router/blob/main/docs/reference/index.md
Sets up a new router instance with the given routes configuration. Returns a router API object with navigation and route-related properties.
```APIDOC
## createRouter(routes)
### Description
Sets up a new router instance with the given routes configuration.
### Parameters
- `routes` - An object mapping paths to components or nested routes
### Returns
A router API object with the following properties:
- [`p`](#p-path-params)
- [`navigate`](#navigate-path-options)
- [`isActive`](#isactive-path-params)
- [`preload`](#preload-path)
- [`route`](#route)
```
--------------------------------
### Reactive Search Params
Source: https://github.com/colinlienard/sv-router/blob/main/AGENTS.md
Manage URL search parameters with a reactive wrapper. Supports standard `get`, `set`, and `delete` methods, and automatically updates the URL.
```javascript
const { searchParams } = createRouter({});
// Example usage:
searchParams.set('query', 'sv-router');
console.log(searchParams.get('query'));
```
--------------------------------
### File-Based Routing Entry Point
Source: https://context7.com/colinlienard/sv-router/llms.txt
Set up the App.svelte file to use file-based routing. Importing 'sv-router/generated' registers the routes automatically based on your file structure.
```svelte
HomeAbout
```
--------------------------------
### Manage Search Parameters with sv-router
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/search-params.md
Import and use the searchParams object to add, delete, and get URL parameters. Effects can be used to react to changes in parameter values.
```typescript
import { searchParams } from 'sv-router';
// Add a parameter
searchParams.append('hello', 'world');
// Remove a parameter
searchParams.delete('hello');
// React to parameter changes
$effect(() => {
// This effect will re-run whenever the 'hello' parameter changes
const value = searchParams.get('hello');
console.log('Hello parameter is now:', value);
});
```
--------------------------------
### Create SV Router with PNPM
Source: https://github.com/colinlienard/sv-router/blob/main/create/README.md
Use this command to create a new SV Router project with PNPM.
```bash
pnpm create sv-router
```
--------------------------------
### Render Router and Add Navigation Links
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/manual-setup.md
Import and use the `Router` component in your application's entry point to render active routes. Add navigation links using standard `` tags with `href` attributes pointing to your defined routes.
```svelte
HomeAbout
```
--------------------------------
### Create SV Router with Yarn
Source: https://github.com/colinlienard/sv-router/blob/main/create/README.md
Use this command to create a new SV Router project with Yarn.
```bash
yarn create sv-router
```
--------------------------------
### Create New Project with sv-router
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/getting-started.md
Use this command to scaffold a new Svelte 5 project with sv-router pre-configured. Choose your preferred package manager.
```sh
npm create sv-router@latest
```
```sh
pnpm create sv-router
```
```sh
yarn create sv-router
```
```sh
bun create sv-router
```
```sh
deno run -A npm:create-sv-router@latest
```
--------------------------------
### Directory structure for catch-all routes ignoring layouts
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/layouts.md
Illustrates how to create a catch-all route that ignores its parent layout by wrapping the catch-all segment in parentheses.
```sh
# Catch-all route that ignores parent layout
routes
└── ([...notfound]).svelte
```
--------------------------------
### Define a Catch-All Route
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/catch-all-routes.md
Use the spread syntax in a filename to create a catch-all route. This will match any path not explicitly defined by other routes. The unmatched segments are available in `route.params`.
```sh
routes
└── [...notfound].svelte ➜ /any-path
```
--------------------------------
### Directory structure for dynamic routes ignoring layouts
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/layouts.md
Demonstrates how to create a dynamic route that ignores its parent layout by wrapping the dynamic segment in parentheses.
```sh
# Dynamic route that ignores parent layout
routes
└── ([id]).svelte
```
--------------------------------
### Reactive URL Search Parameters with sv-router
Source: https://context7.com/colinlienard/sv-router/llms.txt
Use `searchParams` to manage URL query parameters reactively. It automatically updates the browser URL and Svelte reactivity. Supports `get`, `set`, and `delete` operations, with an option to replace the history entry.
```svelte
Active filter: {filter}
```
--------------------------------
### navigate(path, options?)
Source: https://github.com/colinlienard/sv-router/blob/main/docs/reference/index.md
Programmatically navigates to a route. Returns a promise that resolves once the navigation is complete, including redirects and lazy-loaded components.
```APIDOC
## navigate(path, options?)
### Description
Programmatically navigate to a route. Returns a promise that resolves once the navigation is complete, including any redirects triggered by `beforeLoad` hooks and lazy-loaded route components.
### Parameters
- `path | number` - Either:
- A string path to navigate to, or
- A number representing steps to navigate in history (negative for back, positive for forward)
- `options` - (Optional) Navigation options
- `replace` - Replace current history entry instead of pushing
- `search` - Query string
- `state` - History state to save
- `hash` - URL hash fragment
- `scrollToTop` - Scroll behavior (`"auto" | "instant" | "smooth" | false`)
- `viewTransition` - Enable view transition (`boolean`)
- `params` - Parameters to substitute in the path
### Returns
`Promise` - Resolves when the full navigation (including redirects and code splitting) is complete
```
--------------------------------
### File-based Hooks Directory Structure
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/hooks.md
Demonstrates the correct directory structure for placing a `hooks.ts` file within a route directory.
```sh
routes
└── about
├── hooks.ts
└── index.svelte
```
--------------------------------
### Link Navigation with Parameters and Options
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Pass parameters, search queries, and state to the `p` function for dynamic route generation. Use `data-replace` to replace the current history entry and `data-state` to pass custom state.
```svelte
A post
```
--------------------------------
### Development Commands
Source: https://github.com/colinlienard/sv-router/blob/main/AGENTS.md
Common development commands for the sv-router project, including testing, linting, formatting, and building documentation and CLI tools.
```bash
pnpm test
pnpm test:coverage
pnpm check
pnpm lint
pnpm lint:fix
pnpm format
pnpm format:fix
pnpm docs:dev
pnpm docs:build
pnpm create:dev
pnpm create:build
pnpm changeset
```
--------------------------------
### Run ESLint for Linting
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Check code for style and potential errors using ESLint with the `pnpm lint` command. This command enforces a zero-warnings tolerance.
```bash
pnpm lint
```
--------------------------------
### p(path, params?)
Source: https://github.com/colinlienard/sv-router/blob/main/docs/reference/index.md
Constructs a path with type-safe parameter substitution, including optional parameters, search queries, and hash fragments.
```APIDOC
## p(path, params?)
### Description
Constructs a path with type-safe parameter substitution.
### Parameters
- `path` - The route path
- `options` - (Optional) Navigation options
- `params` - Parameters to substitute in the path
- `search` - Query string
- `hash` - URL hash fragment
### Returns
A string representing the constructed path
```
--------------------------------
### Define Routes with createRouter
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/manual-setup.md
Define your application's routes and export router methods. This file should be imported in your application's entry point.
```typescript
import { createRouter } from 'sv-router';
import Home from './routes/Home.svelte';
import About from './routes/About.svelte';
export const { p, navigate, isActive, route } = createRouter({
'/': Home,
'/about': About,
});
```
--------------------------------
### Programmatic Preloading
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Initiate route preloading programmatically using the `preload()` function. This allows for more control over when and which routes are preloaded.
```javascript
preload()
```
--------------------------------
### Define a Basic Catch-All Route
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/catch-all-routes.md
Use the `*` symbol to define a route that matches any unmatched URL. This is typically used to render a 404 Not Found component.
```typescript
'*': NotFound,
```
--------------------------------
### Configure Link-Based Preloading Strategies
Source: https://context7.com/colinlienard/sv-router/llms.txt
Control when route components are preloaded using data attributes on anchor tags. Options include preloading on hover (default), when the link enters the viewport, or based on predicted pointer movement.
```svelte
DashboardDashboardDashboard
```
--------------------------------
### Directory structure for layouts
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/layouts.md
Illustrates the file structure for implementing layouts in file-based routing. The layout.svelte file defines the shared UI for routes within its directory.
```sh
routes
└── about
├── index.svelte
├── layout.svelte
├── team.svelte
└── work.svelte
```
--------------------------------
### Create a Changeset for Release
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Generate a changeset for managing package versions and changelogs by running `pnpm changeset`. This is part of the release workflow using Changesets.
```bash
pnpm changeset
```
--------------------------------
### Preloading Strategy: Hover
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Enable preloading of routes by adding the `data-preload` attribute to `` tags. The default strategy is 'hover', which preloads links when the mouse hovers over them.
```html
Link
```
--------------------------------
### File-Based Layout Structure
Source: https://context7.com/colinlienard/sv-router/llms.txt
Organize routes with layouts in file-based routing by placing a `layout.svelte` file in the directory. This layout will wrap all sibling routes within that directory.
```sh
# File-based layout
src/routes/app/
├── layout.svelte # wraps index + profile
├── index.svelte ➜ /app
├── profile.svelte ➜ /app/profile
└── (onboarding).svelte ➜ /app/onboarding (no layout)
```
--------------------------------
### Import and Use Router Component
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/manual-setup.md
Import the Router component and the generated routes in your application's entry point (e.g., App.svelte) to enable navigation.
```svelte
HomeAbout
```
--------------------------------
### Basic Link Navigation
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Use standard anchor tags for basic navigation between pages.
```svelte
About
```
--------------------------------
### Programmatic Navigation with navigate()
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/navigation.md
Use the `navigate` function for JavaScript-triggered navigation, offering auto-completion and type checking. Ensure `sv-router/generated` is imported.
```svelte
```
--------------------------------
### Blocking Tab Close and Navigation
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Use the object form of `blockNavigation` to configure both navigation blocking (`onNavigate`) and tab closing (`beforeUnload`). Note that `beforeUnload` must be synchronous.
```svelte
```
--------------------------------
### Check Route Activation with `isActive`
Source: https://context7.com/colinlienard/sv-router/llms.txt
Use `isActive` for type-safe route activation checks, supporting exact and parameter-based matching. `isActive.startsWith` is available for prefix matching.
```typescript
import { isActive } from './router';
// Exact match
isActive('/about'); // true when on /about
// Match with specific param value
isActive('/post/:slug', { slug: '123' }); // true when on /post/123
// Match any value for a param
isActive('/post/:slug'); // true when on /post/*
// Prefix match (also matches /about/team, /about/work, etc.)
isActive.startsWith('/about'); // true when on /about or any sub-route
```
```svelte
Dashboard
```
--------------------------------
### Configure Netlify Redirects for SPAs
Source: https://context7.com/colinlienard/sv-router/llms.txt
Set up redirects on Netlify to serve `index.html` for all routes, enabling client-side routing for your SPA. This configuration ensures that all requests are handled by the frontend router.
```toml
# Netlify — _redirects file
/* /index.html 200
```
--------------------------------
### Check Prettier Formatting
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Verify code formatting against Prettier standards by running `pnpm format`. This command checks for consistency without making changes.
```bash
pnpm format
```
--------------------------------
### Programmatic Navigation with navigate()
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Use the `navigate` function for JavaScript-triggered navigation, offering auto-complete and type checking. Ensure `navigate` is imported from the router.
```svelte
```
--------------------------------
### Preloading Strategy: Viewport
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Configure preloading to trigger when links enter the viewport by setting the `data-preload` attribute to `"viewport"`. This ensures routes are preloaded as they become visible.
```html
Link
```
--------------------------------
### `navigate(path, options?)` — Programmatic Navigation
Source: https://context7.com/colinlienard/sv-router/llms.txt
Navigates to a route programmatically. Returns a `Promise` that resolves after the full navigation completes. Supports history traversal with a numeric delta argument.
```APIDOC
## `navigate(path, options?)` — Programmatic Navigation
Navigates to a route programmatically. Returns a `Promise` that resolves after the full navigation completes, including `beforeLoad` hooks and lazy-loaded components. Supports history traversal with a numeric delta argument.
### Method
```ts
navigate(path: string | number, options?: {
params?: Record;
search?: Record;
hash?: string;
state?: any;
replace?: boolean;
scrollToTop?: 'smooth' | false;
viewTransition?: boolean;
}): Promise;
```
### Parameters
- **path** (string | number) - The path to navigate to, or a number for history traversal.
- **options** (object, optional) - Configuration for the navigation.
- **params** (object, optional) - Dynamic parameters for the path.
- **search** (object, optional) - Query parameters for the URL.
- **hash** (string, optional) - The URL hash fragment.
- **state** (any, optional) - State to be passed with the navigation.
- **replace** (boolean, optional) - If true, replaces the current history entry.
- **scrollToTop** ('smooth' | false, optional) - Controls scrolling to the top of the page.
- **viewTransition** (boolean, optional) - If true, enables View Transitions API for animated transitions.
### Examples
```ts
// Basic navigation
await navigate('/about');
// With dynamic params, search, hash, and state
await navigate('/post/:slug', {
params: { slug: 'hello-world' },
search: { page: '2', filter: 'recent' },
hash: 'comments',
state: { from: '/home' },
});
// Replace current history entry
await navigate('/dashboard', { replace: true });
// Smooth scroll-to-top
await navigate('/about', { scrollToTop: 'smooth' });
// Animated page transition
await navigate('/about', { viewTransition: true });
// Disable scroll-to-top
await navigate('/modal', { scrollToTop: false });
// History traversal
navigate(-1); // go back one step
navigate(1); // go forward one step
```
```
--------------------------------
### Enable Hash-based Routing
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/basename.md
Using '#' as the base for the Router component enables hash-based routing. Routes are matched by the URL's hash instead of its pathname, making it suitable for file:// URLs.
```svelte
```
--------------------------------
### File-Based Routing Conventions
Source: https://github.com/colinlienard/sv-router/blob/main/AGENTS.md
Auto-generates routes from files in src/routes/. Conventions include index.svelte for root, [id].svelte for dynamic routes, layout.svelte for wrappers, hooks.ts for guards, and (groupName)/ for layout groups.
```javascript
// File conventions:
// index.svelte → /
// about.svelte → /about
// [id].svelte → /:id (dynamic)
// [...catch].svelte → catch-all
// layout.svelte → wraps sibling/child routes
// hooks.ts → route hooks for that directory
// (groupName)/ → layout groups (not in URL)
```
--------------------------------
### Programmatic Navigation with Parameters and Options
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Pass parameters, replace history, add search queries, state, and hash to the `navigate` function for flexible programmatic navigation.
```typescript
navigate('/post/:slug', {
params: {
slug: '123',
},
replace: true,
search: { q: 'hello' },
state: { from: 'home' },
hash: 'first-section',
});
```
--------------------------------
### File-Based Lazy Loading via Filename Suffix
Source: https://context7.com/colinlienard/sv-router/llms.txt
Configure file-based routing to automatically lazy-load components by appending `.lazy.svelte` to their filenames. Alternatively, set `allLazy: true` in the Vite plugin.
```sh
# File-based: lazy route via filename suffix
src/routes/
├── index.svelte
├── about.lazy.svelte # lazy-loaded
└── dashboard.lazy.svelte # lazy-loaded
```
--------------------------------
### Run Vitest Tests with Coverage
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Generate a test coverage report by running `pnpm test:coverage`. This command executes tests and provides detailed coverage information.
```bash
pnpm test:coverage
```
--------------------------------
### Importing Generated Router Utilities
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/route-definition.md
Access generated router exports like navigate from the 'sv-router/generated' entry point. This is used for navigation and route management.
```typescript
import { navigate, ... } from 'sv-router/generated';
```
--------------------------------
### Create Route Generation Script
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/manual-setup.md
Add a script to your package.json to generate routes using the sv-router CLI.
```json
{
"scripts": {
"gen-routes": "sv-router" // [!code ++]
}
}
```
--------------------------------
### router(options?)
Source: https://github.com/colinlienard/sv-router/blob/main/docs/reference/vite-plugin.md
A Vite plugin that automatically generates route definitions from your file system structure. It accepts an optional configuration object to customize its behavior.
```APIDOC
## router(options?)
### Description
A Vite plugin that automatically generates route definitions from your file system structure.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- `options` - (Optional) Configuration object for the router plugin. See `RouterOptions` for details.
### Returns
- A Vite plugin
```
--------------------------------
### Programmatic Navigation with navigate()
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Navigate programmatically using the `navigate()` function. Supports navigating to a specific path or back using `navigate(-1)`. Ensures compile-time validation.
```javascript
navigate(path, opts?)
```
--------------------------------
### preload(path)
Source: https://github.com/colinlienard/sv-router/blob/main/docs/reference/index.md
Preloads route components for a given path, returning a promise that resolves upon completion.
```APIDOC
## preload(path)
### Description
Preload route components.
### Parameters
- `path` - The route to preload
### Returns
Promise that resolves when the route components are preloaded
```
--------------------------------
### Preloading Links
Source: https://github.com/colinlienard/sv-router/blob/main/AGENTS.md
Enable preloading for `` tags by adding the `data-preload` attribute. Supports hover, viewport, and predictive preloading strategies.
```html
About
```
--------------------------------
### `p(path, options?)` — Type-safe Path Constructor
Source: https://context7.com/colinlienard/sv-router/llms.txt
Constructs a type-safe URL string. Used in `href` attributes to ensure broken links are caught at compile time. Accepts params, search, and hash.
```APIDOC
## `p(path, options?)` — Type-safe Path Constructor
Constructs a type-safe URL string. Used in `href` attributes to ensure broken links are caught at compile time. Accepts params, search, and hash.
### Method
```ts
p(path: string, options?: {
params?: Record;
search?: Record;
hash?: string;
}): string;
```
### Parameters
- **path** (string) - The base path.
- **options** (object, optional) - Configuration for path construction.
- **params** (object, optional) - Dynamic parameters for the path.
- **search** (object, optional) - Query parameters for the URL.
- **hash** (string, optional) - The URL hash fragment.
### Examples
```svelte
HomeMy Post
My Post
Next StepAboutAbout (smooth scroll)Open Modal
```
```
--------------------------------
### Type-Safe Link Navigation with p()
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/navigation.md
Leverage the `p` function for type-safe navigation, providing auto-completion and type checking for your routes. Ensure `sv-router/generated` is imported.
```svelte
About
```
--------------------------------
### Preloading Strategy: Predict
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Utilize the 'predict' strategy for preloading, which uses cone-based pointer prediction to anticipate user navigation. This can be set via the `data-preload` attribute.
```html
Link
```
--------------------------------
### Run Vitest Tests
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Execute all tests using the `pnpm test` command. This command utilizes Vitest with a happy-dom environment and associated testing libraries.
```bash
pnpm test
```
--------------------------------
### Enable View Transitions with data-view-transition attribute
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/view-transitions.md
Add the `data-view-transition` attribute to an anchor tag to enable view transitions for link-based navigation. Falls back to regular navigation if the API is not supported.
```svelte
About
```
--------------------------------
### Directory structure for breaking out of layouts
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/layouts.md
Shows how to exclude a route from inheriting its parent layout by wrapping the route segment in parentheses. This allows specific routes to bypass shared layouts.
```sh
routes
└── about
├── index.svelte ➜ Uses layout
├── layout.svelte
└── work
├── index.svelte ➜ Uses layout
└── (clients).svelte ➜ Ignores layout
```
--------------------------------
### route
Source: https://github.com/colinlienard/sv-router/blob/main/docs/reference/index.md
Provides access to the current route's information, including parameters, pathname, search, state, and hash.
```APIDOC
## route
### Description
An object containing information about the current route.
### Properties
- `params` - Non-strict parameters from the current route
- `getParams(pathname: string)` - Strict parameters from the current route
- `pathname` - Current path
- `search` - Query string portion of the URL
- `state` - History state
- `hash` - Hash fragment of the URL
```
--------------------------------
### Build Type-Safe URL with p()
Source: https://github.com/colinlienard/sv-router/blob/main/CLAUDE.md
Use the `p()` helper to construct type-safe URLs, including path parameters, search parameters, and hash fragments. Ensures compile-time validation of paths and params.
```javascript
p(path, opts?)
```
--------------------------------
### Type-Safe Link Navigation with p()
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Leverage the `p` function for type-safe navigation, providing auto-complete and type checking for routes. Ensure `p` is imported from the router.
```svelte
About
```
--------------------------------
### Async Navigation Blocking
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/navigation.md
Implement asynchronous navigation blocking by providing an async callback to `blockNavigation`. This is useful for performing asynchronous operations like showing custom modals before deciding to allow navigation.
```svelte
```
--------------------------------
### Enable View Transitions with navigate()
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/view-transitions.md
Pass the `viewTransition: true` option to the `navigate` function to enable view transitions for code-based navigation. Falls back to regular navigation if the API is not supported.
```typescript
navigate('/about', { viewTransition: true });
```
--------------------------------
### Implement Code Splitting with Dynamic Import
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/code-based/code-splitting.md
Use dynamic import() to lazy-load routes, reducing initial bundle size. This is useful for routes that are not immediately needed.
```typescript
import { createRouter } from 'sv-router';
import Home from './routes/Home.svelte';
import About from './routes/About.svelte'; // [!code --]
export const { p, navigate, isActive, route } = createRouter({
'/': Home,
'/about': About, // [!code --]
'/about': () => import('./routes/About.svelte'), // [!code ++]
});
```
--------------------------------
### Construct Type-Safe Paths with `p`
Source: https://context7.com/colinlienard/sv-router/llms.txt
Use `p` to create type-safe URL strings for `href` attributes, catching broken links at compile time. It accepts dynamic parameters, search queries, and hash fragments.
```svelte
HomeMy Post
My Post
Next StepAboutAbout (smooth scroll)Open Modal
```
--------------------------------
### Manage Head with svelte:head
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/tips.md
Use Svelte's native `` element to dynamically manage metadata like page titles and meta tags for each route.
```svelte
About
```
--------------------------------
### Navigate Programmatically with Options
Source: https://context7.com/colinlienard/sv-router/llms.txt
Use `navigate` for programmatic navigation. Supports dynamic parameters, search, hash, state, history replacement, scroll behavior, and view transitions. Can also be used for history traversal with numeric arguments.
```typescript
import { navigate } from './router';
// Basic navigation
await navigate('/about');
// With dynamic params, search, hash, and state
await navigate('/post/:slug', {
params: { slug: 'hello-world' },
search: { page: '2', filter: 'recent' },
hash: 'comments',
state: { from: '/home' },
});
// Replace current history entry (no new history entry)
await navigate('/dashboard', { replace: true });
// Smooth scroll-to-top on navigation
await navigate('/about', { scrollToTop: 'smooth' });
// Animated page transition via the View Transitions API
await navigate('/about', { viewTransition: true });
// Disable scroll-to-top
await navigate('/modal', { scrollToTop: false });
// History traversal (back / forward)
navigate(-1); // go back one step
navigate(1); // go forward one step
navigate(-2); // go back two steps
```
--------------------------------
### Configure Server-Side Fallback for SPAs
Source: https://context7.com/colinlienard/sv-router/llms.txt
For Single Page Applications using sv-router, configure the server to fallback to `index.html` for all routes. This is essential for client-side routing to work correctly after the initial load.
```nginx
server {
location / {
try_files $uri $uri/ /index.html;
}
}
```
--------------------------------
### Suffix Route Files with .lazy.svelte
Source: https://github.com/colinlienard/sv-router/blob/main/docs/guide/file-based/code-splitting.md
To implement code splitting, suffix your route filename with .lazy.svelte. This applies to individual route files.
```sh
routes
├── about.svelte # [!code --]
├── about.lazy.svelte # [!code ++]
└── index.svelte
```