Router
The Svelte router ships with AbsoluteJS. Guards decide whether a navigation happens, in the browser and during the server render. Lazy routes load a component only when it is needed. Scroll positions are kept across back and forward.
#Setup
Import Router, Route and Link by file path from @absolutejs/absolute/svelte/router/*.svelte. Functions and types such as goto, redirect and NavigationContext come from @absolutejs/absolute/svelte/router. The Svelte SPA page covers routes, params, links and goto.
Pass request to the page handler. The handler sets props.url from it, and guards get it while the page renders on the server.
// backend/server.ts
import { asset } from '@absolutejs/absolute';
import { handleSveltePageRequest } from '@absolutejs/absolute/svelte';
import type App from '../frontend/svelte/pages/App.svelte';
const appPage = ({ request }: { request: Request }) =>
handleSveltePageRequest<typeof App>({
indexPath: asset(manifest, 'AppIndex'),
pagePath: asset(manifest, 'App'),
props: {},
request // passed to guards; also sets props.url
});
new Elysia()
.get('/app', appPage)
.get('/app/*', appPage);#Route Guards
A guard is a function that runs before a navigation commits. Put one on a Route to protect that route. It runs for Link clicks, goto(), back and forward, and the server render. Guards can be async.
<!-- frontend/svelte/pages/App.svelte -->
<script lang="ts">
import Route from '@absolutejs/absolute/svelte/router/Route.svelte';
import Router from '@absolutejs/absolute/svelte/router/Router.svelte';
import Dashboard from '../components/Dashboard.svelte';
import Login from '../components/Login.svelte';
import { requireUser } from '../utils/session';
let { url }: { url?: string } = $props();
</script>
<Router {url}>
<Route path="/app/login">
{#snippet content()}<Login />{/snippet}
</Route>
<Route
path="/app/dashboard"
guard={({ request }) => requireUser(request, '/app/dashboard')}
>
{#snippet content()}<Dashboard />{/snippet}
</Route>
</Router>redirect() returns a value you can return or throw. Throwing it from a helper deep inside a guard stops the guard chain the same way. Any other error a guard throws rejects the navigation.
// frontend/svelte/utils/session.ts
import { redirect } from '@absolutejs/absolute/svelte/router';
// request is set during the server render and undefined in the browser.
// The browser can only read cookies that are not httpOnly, so this
// checks a signed_in flag set next to the real session cookie.
const readCookies = (request: Request | undefined) =>
request ? (request.headers.get('cookie') ?? '') : document.cookie;
export const requireUser = (request: Request | undefined, next: string) => {
if (!readCookies(request).includes('signed_in=1')) {
throw redirect(`/app/login?next=${encodeURIComponent(next)}`);
}
};
export const isAdmin = (request: Request | undefined) =>
readCookies(request).includes('role=admin');#Router Guards
A guard on Router covers a group of routes. On the outermost router it runs for every navigation. On a nested router it runs for navigations onto that router's routes.
<Router
{url}
guard={({ to, request }) => {
if (to.pathname.startsWith('/app/admin') && !isAdmin(request)) {
return '/app/login';
}
}}
>
<Route path="/app/admin">
{#snippet content()}<Admin />{/snippet}
</Route>
</Router>#beforeNavigate
beforeNavigate registers a guard for every client-side navigation. It never runs on the server, so use it for browser concerns such as unsaved changes. Put checks the server must enforce on a Route or Router guard. Called during component setup, the guard is removed when the component is destroyed. It also returns a function that removes it.
<script lang="ts">
import { beforeNavigate } from '@absolutejs/absolute/svelte/router';
let dirty = $state(false);
// Browser only. Registered while the component sets up, it is
// removed when the component is destroyed.
beforeNavigate(() => {
if (dirty) return false;
});
</script>For one navigation the guards run in this order, and the first guard that cancels or redirects decides: beforeNavigate guards in registration order, then each mounted Router guard outermost first, then the matched Route guard.
| Guard | Runs | Scope |
|---|---|---|
beforeNavigate(fn) | Browser only | Every client-side navigation |
<Router guard> | Browser and server | Outermost router: every navigation. Nested router: navigations onto its routes. |
<Route guard> | Browser and server | Navigations onto that route |
#Guard Results
Every guard receives a NavigationContext and returns a RouteGuardResult. Both types are exported from @absolutejs/absolute/svelte/router.
// Exported as types from '@absolutejs/absolute/svelte/router'
type NavigationContext = {
from: URL | null; // null on the first render ('enter')
to: URL; // in hash mode, to.pathname is the routed path
params: Record<string, string | undefined>; // the guard's route, matched against to
type: 'link' | 'goto' | 'popstate' | 'enter';
request: Request | undefined; // the incoming request, server render only
};
type RouteGuardResult =
| undefined
| void
| boolean // true allows, false cancels
| string // redirect to this URL
| { redirect: string; replace?: boolean };
type RouteGuard = (
navigation: NavigationContext
) => RouteGuardResult | Promise<RouteGuardResult>;| Result | Effect |
|---|---|
undefined | Allow the navigation |
true | Allow the navigation |
false | Cancel: the URL and the route stay as they were |
'/app/login' | Redirect to that URL |
{ redirect: '/app/login', replace: true } | Redirect, replacing the current history entry |
redirect('/app/login') | Redirect. Return it or throw it. |
When you cancel back or forward, the router puts the previous URL back. A redirect from back, forward or the first render always replaces the history entry. goto() resolves to what happened.
import { goto } from '@absolutejs/absolute/svelte/router';
const outcome = await goto('/app/admin');
// 'committed' | 'cancelled' | 'redirected' | 'superseded' | 'external'
if (outcome === 'redirected') {
// a guard sent the navigation somewhere else
}Changing only the #hash runs no guards, and neither does shallow routing with pushState or replaceState.
#Server Redirects
When the handler gets request, each Router runs its Router and Route guards against the request URL during the server render. The context has type: 'enter', from: null and request set, so a guard can read cookies and headers. The result becomes a real response.
| Guard result | Status | Response |
|---|---|---|
| Redirect | 302 | Location is the target. A same-origin target is written as a path. |
false | 403 | The request ends with 403 Forbidden. |
| Allow | 200 | The page renders as usual. |
Keep guard logic the same on both sides for the same input. The server HTML is what hydrates, and the guard runs again on the next navigation. In hash mode the server never sees the hash, so the router also runs the guards once in the browser on the first render.
#Lazy Routes
Give a Route a loader instead of a content snippet. The build puts the component in its own chunk. The browser loads it the first time the route is visited or a Link to it is prefetched.
<Route
path="/app/editor/:id"
loader={() => import('../components/Editor.svelte')}
props={{ readOnly: false }}
>
{#snippet pending()}<p>Loading the editor…</p>{/snippet}
{#snippet error(reason, retry)}
<p>The editor failed to load.</p>
<button onclick={retry}>Try again</button>
{/snippet}
</Route>The component receives the route params as props, plus anything in props. The props value is type-checked against the component's props minus the route params. pending shows while a client-side navigation waits for the chunk. error gets the reason and a retry function. With no error snippet, a failed load is thrown again.
<!-- frontend/svelte/components/Editor.svelte -->
<script lang="ts">
// id comes from the route params, readOnly from the props prop.
let { id, readOnly }: { id: string; readOnly: boolean } = $props();
</script>
<h1>Editing {id}</h1>On the server the page handler waits for the loader and renders the real component, so the HTML is complete. The browser loads that chunk before it hydrates, so the page shows no pending state and hydration matches. To warm a chunk yourself, call preloadRoute.
import { preloadRoute } from '@absolutejs/absolute/svelte/router';
// Start loading the chunk for the route this URL would render.
preloadRoute('/app/editor/7');#Scroll Restoration
While a Router is mounted it manages the window's scroll position. It sets history.scrollRestoration to 'manual' on mount and puts the old value back on unmount.
| Navigation | Scroll position |
|---|---|
<Link> | Top of the page, or the #hash target when the URL has one |
goto(url) | Same as a link |
| Back / forward | The position you were at when you left that entry |
| Reload | The position saved in the entry |
noScroll | Unchanged. Pass it to goto() or set it on <Link>. |
pushState / replaceState | Unchanged (shallow routing) |
<script lang="ts">
import Link from '@absolutejs/absolute/svelte/router/Link.svelte';
import { goto } from '@absolutejs/absolute/svelte/router';
const showTab = (tab: string) =>
goto(`/app/docs?tab=${tab}`, { noScroll: true });
</script>
<!-- Scrolls the element with id="install" into view -->
<Link to="/app/docs#install">Install</Link>
<!-- Keeps the current scroll position -->
<Link to="/app/docs?tab=api" noScroll>API tab</Link>
<button onclick={() => showTab('examples')}>Examples</button>In hash mode the hash holds the route, so navigations scroll to the top and back and forward restore the saved position. The router tracks the window only, not inner scroll containers.