https://github.com/bmlt-enabled/svelte-spa-router
https://github.com/bmlt-enabled/svelte-spa-router
Last synced: 4 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/bmlt-enabled/svelte-spa-router
- Owner: bmlt-enabled
- License: mit
- Created: 2026-01-06T00:04:57.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2026-06-19T12:14:47.000Z (11 days ago)
- Last Synced: 2026-06-19T14:14:24.360Z (11 days ago)
- Language: JavaScript
- Size: 2.36 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# @bmlt-enabled/svelte-spa-router
This module is a router for [Svelte 5](https://github.com/sveltejs/svelte) applications, specifically optimized for Single Page Applications (SPA).
Main features:
- Supports both **hash-based routing** (default) and **History API path-based routing** for clean URLs
- Insanely simple to use, and has a minimal footprint
- Uses a vendored copy of the tiny [regexparam](https://github.com/lukeed/regexparam) for parsing routes, with support for parameters (e.g. `/book/:id?`) and more
This module is released under MIT license, forked from [ItalyPaleAle/svelte-spa-router](https://github.com/ItalyPaleAle/svelte-spa-router).
## Routing modes
### Hash-based routing (default)
With hash-based routing, navigation is possible thanks to storing the current view in the part of the URL after `#`, called "hash" or "fragment".
For example, if your SPA is in a static file called `index.html`, your URLs for navigating within the app look something like `index.html#/profile`, `index.html#/book/42`, etc. (The `index.html` part can usually be omitted for the index file, so you can just create URLs that look like `http://example.com/#/profile`).
Hash-based routing is simpler, works well even without a server, and it's generally better suited for static SPAs, especially when SEO isn't a concern, as is the case when the app requires authentication. Many popular apps use hash-based routing, including GMail!
### Path-based routing (History API)
If you prefer clean URLs without the `#` fragment (e.g. `http://example.com/profile` instead of `http://example.com/#/profile`), you can enable path-based routing using the History API by setting `hashMode={false}` on the Router component:
```svelte
```
All other APIs (`push`, `pop`, `replace`, `use:link`, `use:active`, route definitions) work exactly the same in both modes. No changes to your route definitions or navigation code are needed.
#### Base path
When your app is served under a sub-path (e.g. `example.com/meetings/`), you can set a `basePath` so the router automatically strips it from incoming URLs and prepends it to outgoing ones:
```svelte
```
Or programmatically:
```js
import { setHashMode } from '@bmlt-enabled/svelte-spa-router'
setHashMode(false, '/meetings')
```
With `basePath="/meetings"`, `push('/book/42')` navigates to `/meetings/book/42`, and `router.location` returns `/book/42` — your app code never needs to know about the prefix.
**Important:** When using path-based routing, your server must be configured to serve your `index.html` for all routes (SPA fallback). Without this, refreshing the page or navigating directly to a URL like `/books` will result in a 404 from the server. Common configurations:
- **Nginx:** `try_files $uri $uri/ /index.html;`
- **Apache:** Use `FallbackResource /index.html` or a rewrite rule
- **Vite dev server:** Already handles this by default
- **Static hosts (Netlify, Vercel):** Add a `_redirects` or `vercel.json` rewrite rule
## Sample code
Check out the code in the [examples](/examples) folder for some usage examples.
To run the example, clone the repository, install the dependencies, then start the dev server:
```sh
git clone https://github.com/bmlt-enabled/svelte-spa-router
cd svelte-spa-router
npm install
# Hash-mode example
npm run dev:example
# Path-mode example (History API)
npm run dev:example-path
# Test app (hash mode)
npm run dev:test
# Test app (path mode / History API)
npm run dev:test-path
```
- Example app (hash mode): http://localhost:5050
- Example app (path mode): http://localhost:5054
- Test app (hash mode): http://localhost:5051
- Test app (path mode): http://localhost:5052
## Using @bmlt-enabled/svelte-spa-router
You can include the router in any project using Svelte 5.
### Install from NPM
```sh
npm install @bmlt-enabled/svelte-spa-router
```
### Supported browsers
@bmlt-enabled/svelte-spa-router aims to support modern browsers, including recent versions of:
- Chrome
- Edge ("traditional" and Chromium-based)
- Firefox
- Safari
### Define your routes
Each route is a normal Svelte component, with the markup, scripts, bindings, etc. Any Svelte component can be a route.
The route definition is just a JavaScript dictionary (object) where the key is a string with the path (including parameters, etc), and the value is the route object.
For example:
```js
import Home from './routes/Home.svelte'
import Author from './routes/Author.svelte'
import Book from './routes/Book.svelte'
import NotFound from './routes/NotFound.svelte'
const routes = {
// Exact path
'/': Home,
// Using named parameters, with last being optional
'/author/:first/:last?': Author,
// Wildcard parameter
'/book/*': Book,
// Catch-all
// This is optional, but if present it must be the last
'*': NotFound,
}
```
Routes must begin with `/` (or `*` for the catch-all route).
Alternatively, you can also define your routes using custom regular expressions, as explained below.
Note that the order matters! When your users navigate inside the app, the first matching path will determine which route to load. It's important that you leave any "catch-all" route (e.g. a "Page not found" one) at the end.
### Include the router view
To display the router, in a Svelte component (usually `App.svelte`), first import the router component:
```js
import Router from '@bmlt-enabled/svelte-spa-router'
```
Then, display the router anywhere you'd like by placing the component in the markup. For example:
```svelte
```
The `routes` prop is the dictionary defined above. The optional `hashMode` prop controls whether the router uses hash-based URLs (default, `true`) or the History API for clean path-based URLs (`false`). See [Routing modes](#routing-modes) for details.
That's it! You already have all that you need for a fully-functional routing experience.
### Dynamically-imported components and code-splitting
@bmlt-enabled/svelte-spa-router supports dynamically-imported components (via the `import()` construct). The advantage of using dynamic imports is that your bundler can enable code-splitting and reduce the size of the bundle sent to your users.
To use dynamically-imported components, you need to leverage the `wrap` method (which can be used for a variety of actions, as per the docs on [route wrapping](/AdvancedUsage.md#route-wrapping)). First, import the `wrap` method:
```js
import { wrap } from '@bmlt-enabled/svelte-spa-router/wrap'
```
Then, in your route definition, wrap your routes using the `wrap` method, passing a function that returns the dynamically-imported component to the `asyncComponent` property:
```js
wrap({
asyncComponent: () => import('./Foo.svelte'),
})
```
> Note: the value of `asyncComponent` must be the **definition of a function** returning a dynamically-imported component, such as `asyncComponent: () => import('./Foo.svelte')`.
> Do **not** use `asyncComponent: import('./Foo.svelte')`, which is a function invocation instead.
For example, to make the Author and Book routes from the first example dynamically-imported, we'd update the code to:
```js
// Import the wrap method
import { wrap } from '@bmlt-enabled/svelte-spa-router/wrap'
// Note that Author and Book are not imported here anymore, so they can be imported at runtime
import Home from './routes/Home.svelte'
import NotFound from './routes/NotFound.svelte'
const routes = {
'/': Home,
// Wrapping the Author component
'/author/:first/:last?': wrap({
asyncComponent: () => import('./routes/Author.svelte'),
}),
// Wrapping the Book component
'/book/*': wrap({
asyncComponent: () => import('./routes/Book.svelte'),
}),
// Catch-all route last
'*': NotFound,
}
```
The `wrap` method accepts an object with multiple properties and enables other features, including: setting a "loading" component that is shown while a dynamically-imported component is being requested, adding pre-conditions (route guards), passing static props, and adding custom user data.
You can learn more about all the features of `wrap` in the documentation for [route wrapping](/AdvancedUsage.md#route-wrapping).
### Navigating between pages
In hash mode (the default), you can navigate between pages with normal anchor (``) tags using the `#` prefix:
```svelte
Thus Spoke Zarathustra
```
In path mode (`hashMode={false}`), use regular paths:
```svelte
Thus Spoke Zarathustra
```
#### The `use:link` action
The `use:link` action works the same in both modes. You always write paths starting with `/` and the router handles the rest:
Rather than having to type `#` before each link, you can also use the `use:link` action:
```svelte
import { link } from '@bmlt-enabled/svelte-spa-router'
The `use:link` action accepts an optional parameter `opts`, which can be one of:
- A dictionary `{href: '/foo', disabled: false}` where both keys are optional:
- If you set a value for `href`, your link will be updated to point to that address, reactively (this will always take precedence over `href` attributes, if present)
- Setting `disabled: true` disables the link, so clicking on that would have no effect
- A string with a destination (e.g. `/foo`), which is a shorthand to setting `{href: '/foo'}`.
For example:
```svelte
import { link } from '@bmlt-enabled/svelte-spa-router'
let myLink = '/book/456'
The above is equivalent to:
```svelte
import { link } from '@bmlt-enabled/svelte-spa-router'
let myLink = '/book/456'
Changing the value of `myLink` will reactively update the link's `href` attribute.
#### Navigating programmatically
You can navigate between pages programmatically too:
```js
import { push, pop, replace } from '@bmlt-enabled/svelte-spa-router'
// The push(url) method navigates to another page, just like clicking on a link
push('/book/42')
// The pop() method is equivalent to hitting the back button in the browser
pop()
// The replace(url) method navigates to a new page, but without adding a new entry in the browser's history stack
// So, clicking on the back button in the browser would not lead to the page users were visiting before the call to replace()
replace('/book/3')
```
These methods can be used inside Svelte markup too, for example:
```svelte
push('/page')}>Go somewhere
```
The `push`, `pop` and `replace` methods perform navigation actions only in the next iteration ("tick") of the JavaScript event loop. This makes it safe to use them also inside `onMount` callbacks within Svelte components.
These functions return a Promise that resolves with no value once the navigation has been triggered (in the next tick of the event loop); however, please note that this will likely be before the new page has rendered.
### Parameters from routes
@bmlt-enabled/svelte-spa-router uses a vendored copy of [regexparam](https://github.com/lukeed/regexparam) (`regexparam.js`) to parse routes, so you can add optional parameters to the route. Basic syntax is:
- `/path` matches `/path` exactly (and only that)
- `/path/:id` matches `/path/` followed by any string, which is a named argument `id`
- `/path/:id/:version?` allows for an optional second named argument `version`
- `/path/*` matches `/path/` followed by anything, using a non-named argument
_Please refer to [REGEXPARAM.md](REGEXPARAM.md) for more details._
If your route contains any parameter, they will be made available to your component inside the `params` dictionary.
For example, for a route `/name/:first/:last?`, you can create this Svelte component:
```svelte
// You need to define the component prop "params"
let { params = {} } = $props()
Your name is: {params.first}
{#if params.last}{params.last}{/if}
```
Non-named arguments are returned as `params.wild`.
### Getting the current page
You can get the current page from `router.location`.
```svelte
import { router } from '@bmlt-enabled/svelte-spa-router'
The current page is: {router.location}
```
If you need both location and querystring together, use `router.loc`.
### Querystring parameters
You can extract querystring parameters from the URL. In hash mode, these are part of the hash fragment (e.g. `#/books?show=authors,titles&order=1`). In path mode, they come from the real URL querystring (e.g. `/books?show=authors,titles&order=1`).
The router separates the querystring from the location and returns it as a string in `router.querystring`. For example:
```svelte
import { router } from '@bmlt-enabled/svelte-spa-router'
The current page is: {router.location}
The querystring is: {router.querystring}
```
With the example above, this would print:
```text
The current page is: /books
The querystring is: show=authors,titles&order=1
```
To keep this component lightweight, @bmlt-enabled/svelte-spa-router **does not parse** the "querystring". If you want to parse the value of `router.querystring`, you can use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) available in all modern browsers, or third-party modules such as [qs](https://www.npmjs.com/package/qs).
### Highlight active links
@bmlt-enabled/svelte-spa-router has built-in support for automatically marking links as "active", with the `use:active` action.
For example, you can use the code below to add the CSS class `active` to links that are active:
```svelte
import { link } from '@bmlt-enabled/svelte-spa-router'
import active from '@bmlt-enabled/svelte-spa-router/active'
Say hi!
Say hi with a default className!
Say hi with all default options!
/* Style for "active" links; need to mark this :global because the router adds the class directly */
:global(a.active) {
color: red;
}
```
The `active` action accepts a dictionary `options` as argument:
- `options.path`: the path that, when matched, makes the link active. In the first example above, we want the link to be active when the route is `/hello/*` (the asterisk matches anything after that). As you can see, this doesn't have to be the same as the path the link points to. When `options.path` is omitted or false-y, it defaults to the path specified in the link's `href` attribute. This parameter can also be a regular expression that will mark the link as active when it matches: for example, setting to the regular expression `/^\/*\/hi$/` will make the link active when it starts with `/` and ends with `/hi`, regardless of what's in between.
- `options.className`: the name of the CSS class to add. This is optional, and it defaults to `active` if not present.
- `options.inactiveClassName`: the name of the CSS class to add when the link is _not_ active. This is optional, and it defaults to nothing if not present.
As a shorthand, instead of passing a dictionary as `options`, you can pass a single string or regular expression that will be interpreted as `options.path`.
### Define routes with custom regular expressions
It's possible to define routes using custom regular expressions too, allowing for greater flexibility. However, this requires defining routes using a JavaScript Map rather than an object:
```js
import Home from './routes/Home.svelte'
import Name from './routes/Name.svelte'
import NotFound from './routes/NotFound.svelte'
const routes = new Map()
// You can still use strings to define routes
routes.set('/', Home)
routes.set('/hello/:first/:last?', Name)
// The keys for the next routes are regular expressions
// You will very likely always want to start the regular expression with ^
routes.set(/^\/hola\/(.*)/i, Name)
routes.set(/^\/buongiorno(\/([a-z]+))/i, Name)
// Catch-all, must be last
routes.set('*', NotFound)
```
When you define routes as regular expressions, the `params` prop is populated with an array with the result of the matches from the regular expression.
For example, with this `Name.svelte` route:
```svelte
// You need to define the component prop "params"
let { params = {} } = $props()
Params is: {JSON.stringify(params)}
```
When visiting `#/hola/amigos`, the params prop will be `["/hola/amigos","amigos"]`.
This is consistent with the results of [`RegExp.prototype.exec()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec).
> When defining a route using a regular expression, you can optionally use [named capturing groups](https://2ality.com/2017/05/regexp-named-capture-groups.html). When using those, in addition to finding your matches in the `params` prop, you can find the matches for named capturing groups in `params.group`.
> For example, consider the route:
>
> ```js
> routes.set(/^\/book\/(?[a-z]+)$/, Book)
> ```
>
> When visiting `/#/book/mytitle`, the `params` prop will be an array with `["/book/mytitle", "mytitle"]`, and `params.groups` will be a dictionary with `{"title": "mytitle"}`.
## Advanced usage
Check out the [Advanced Usage](/AdvancedUsage.md) documentation for using:
- [Route wrapping](/AdvancedUsage.md#route-wrapping), including:
- [Dynamically-imported routes and placeholders](/AdvancedUsage.md#async-routes-and-loading-placeholders)
- [Route pre-conditions](/AdvancedUsage.md#route-pre-conditions) ("route guards")
- [Adding user data to routes](/AdvancedUsage.md#user-data)
- [Static props](/AdvancedUsage.md#static-props)
- [`onRouteEvent`](/AdvancedUsage.md#onrouteevent)
- [`onRouteLoading` and `onRouteLoaded`](/AdvancedUsage.md#onrouteloading-and-onrouteloaded)
- [Querystring parsing](/AdvancedUsage.md#querystring-parsing)
- [Static props](/AdvancedUsage.md#static-props)
- [Route transitions](/AdvancedUsage.md#route-transitions)
- [Nested routers](/AdvancedUsage.md#nested-routers)
- [Route groups](/AdvancedUsage.md#route-groups)
- [Restore scroll position](/AdvancedUsage.md#restore-scroll-position)
- [Path-based routing (History API)](/AdvancedUsage.md#path-based-routing-history-api)