Navigation: routes, layouts and the screen stack
An app is a stack of screens. Pressing something with href pushes a screen; back pops it and shows the one beneath exactly as it was left. Everything here comes from @duolith/client and the files in pages/.
| To | Write |
|---|---|
| Serve a path | a file in pages/: pages/search.duo is /search |
| Take part of the path | pages/post/[id].duo, then let { id } = route() |
| Take the rest of the path | pages/help/[...topic].duo: /help/a/b gives topic = "a/b" |
| Link to a screen | <view href="/post/7"> or href={/post/${post.id}} |
| Navigate from script | navigate("/post/7"), navigate("/", { replace: true }), back() |
| Wrap screens in shared chrome | pages/_layout.duo with <slot />; nested ones in folders |
| Mark the active tab | current={route().path.startsWith("/feed")}, or the kit's TabBarItem, which does it for you |
| Show a back button only when there is somewhere to go back to | canGoBack() and backTitle(), or the kit's NavHeader |
| Show something for unknown paths | pages/_not-found.duo |
| Keep someone out until a condition holds | guard(() => signedIn || "/sign-in") |
| Share state between screens | state(false, { shared: "signed-in" }) |
| Set the title | <screen title="Feed"> or title={Post ${id}} |
The kit has ready-made parts for this: TabBar and TabBarItem for the tab bar, NavHeader for a screen's header with a back button that appears by itself, Toolbar, Breadcrumbs and Link (kit guide, example examples/navigation-kit).
The runnable example is examples/navigation: a tab bar (Feed, Search, Profile), post detail screens with back, a settings stack inside Profile, a guarded account screen and a not-found screen.
duolith dev examples/navigation --port 4400
Routes
Each file in pages/ serves the path its name gives. index.duo serves its folder.
| File | Serves |
|---|---|
pages/index.duo | / |
pages/search.duo | /search |
pages/profile/index.duo | /profile |
pages/profile/settings/privacy.duo | /profile/settings/privacy |
pages/post/[id].duo | /post/7, /post/hello (one segment, named id) |
pages/help/[...topic].duo | /help/tabs, /help/getting-started/tabs (one or more segments) |
A fixed segment always wins over a parameter, and a parameter over a rest, so pages/post/new.duo serves /post/new even next to pages/post/[id].duo. The build stops with a diagnostic when two files serve the same route (E0141), when two routes would match the same paths, such as post/[id] and post/[slug] (E0142), or when a name is not a valid segment (E0143). Run duolith explain E0142 for any of them.
Files starting with _ are not routes: _layout.duo and pages/_not-found.duo are described below; any other _ name is E0144.
Reading the route
// pages/post/[id].duo
import { route } from "@duolith/client";
let { id } = route(); // "7" for /post/7; always a string
let { query } = route(); // /post/7?tab=likes gives { tab: "likes" }
let { path } = route(); // always decoded: "/café", even when the address says /caf%C3%A9
route() gives the route's parameters, the path and the query. Unpacking a name the route does not have is E0146.
In a page, the route is the one the screen was opened for, and never changes: going from /post/7 to /post/8 opens a new screen, as an app pushes a new view, and back returns to post 7 as it was. So destructure it once at the top.
In a layout, or in any expression, route() is the current route and follows navigation:
<view href="/" current={route().path === "/"}>…</view>
Links and navigating from script
Any element with href is a link. On the web it is an <a>, so it keeps what people expect: open in a new tab with a modifier key or middle click, copy the address. A plain press on a link to a path in the app shows the screen without reloading; links to other sites, links with a #section on the same screen, and presses with a modifier key are left to the browser.
From a script:
import { back, navigate } from "@duolith/client";
navigate("/post/7"); // push
navigate("/profile", { replace: true }); // replace this screen: back skips it
back(); // pop
Every href is a path in the app or an http:, https:, mailto:, tel: or sms: address. Written as text, any other scheme, such as javascript: or data:, is E0170; built from data, the web runtime writes no href for it and logs an error, so a link built from a message or a query string can never run script (decision 0040).
navigate follows only http: and https: addresses, so a javascript: or data: address can never run, whoever wrote it. An address on another site opens with a full page load, and only for a push: a replace, and so a guard's redirect, stays in the app. An address taken from the query string, like the next of a sign-in screen, can still name a page you did not mean, so check it is a path in the app before following it:
let { query } = route();
// "//evil.com" and "/\evil.com" name another site, so only one leading / counts.
const next = query.next?.startsWith("/") && !query.next.startsWith("//") && !query.next.startsWith("/\\") ? query.next : "/";
back() goes to the previous screen of this visit. When the app was opened straight at this screen (a shared link), there is no previous one, so it goes one level up the path instead: from /profile/settings to /profile. If nothing serves the level up (/post for /post/7), that is the not-found screen, so give such pages a link home as well.
The screen stack
A screen you push past stays alive, hidden. Back shows it as you left it: its state, the text typed in its fields, its scroll position, what it loaded. Screens are dropped when you go back past them, when their layout goes away, or when more than ten are kept in one place.
Each screen scrolls on its own and fills the space its layout gives it, as on a phone. Coming back to an entry the screen was dropped for (browser forward, or after a reload) makes the screen again and restores its scroll position.
A page's script runs once for each screen of it, when the screen is made. Effects, derived values and loaded state it starts are stopped when the screen is dropped. Because each screen runs the script again, a page's script cannot export (E0147).
Layouts
A layout wraps every screen in its folder and the folders below it. It shows the screen where it writes <slot /> (a layout without one is E0145):
<!-- pages/_layout.duo -->
---
import { route } from "@duolith/client";
---
<view>
<slot />
<view class="tabs row border-t bg-surface">
<view href="/" current={route().path === "/"} class="tab grow items-center py-2"><text>Feed</text></view>
<view href="/search" current={route().path.startsWith("/search")} class="tab grow items-center py-2"><text>Search</text></view>
</view>
</view>
<style>
.tab { color: var(--color-muted); }
.tab[aria-current] { color: var(--color-primary); }
</style>
Layouts nest: pages/profile/_layout.duo sits inside pages/_layout.duo for every screen under /profile. A layout stays mounted, with its state, while you move between the screens inside it; it is made again only when you leave it. Its script runs once for that whole time, so state there counts across screens (the Profile layout in the example counts the screens opened in its stack).
current={...} marks the active item for assistive technology; on the web it becomes aria-current="page" while true (and no attribute while false), which a style block can select as above.
That is what the kit's TabBar does for you, with icons, badges, safe-area insets and a rail on wide windows:
<view>
<slot />
<TabBar>
<TabBarItem label="Feed" icon="home" href="/" />
<TabBarItem label="Search" icon="search" href="/search" />
</TabBar>
</view>
Going back
back() always does something, but a back button should show only where going back stays in the part of the app the user is in. canGoBack() is true when the screen was pushed from another one (a link inside a screen, or navigate), and backTitle() is that screen's title. A screen a tab opened (a link in a layout), the first screen of a visit and a screen opened from its address have nothing to go back to; a replaced screen keeps what the screen it replaced had. In a page both are fixed when the screen is made; in a layout they follow the screen in front:
<show when={canGoBack()}>
<button label={`Back to ${backTitle() ?? "the last screen"}`} on:press={back}>‹ {backTitle() ?? "Back"}</button>
</show>
Moving to a #section of a screen adds history entries, but back() passes over them to the screen before. A link to the screen the user would reach by going back (such as a breadcrumb to the shelf a book was opened from) goes back to it instead of pushing a copy.
A screen opened straight from its address has nothing to go back to. Give its header the parent route so there is still a way up: <NavHeader title="Post" up="/" upTitle="Feed" /> shows "‹ Feed" (named "Up to Feed") only then, and replaces the screen with the feed.
The kit's NavHeader is that header, ready-made (decision 0041).
Transitions
Only the part of the app that changes moves. Pushing a screen slides it in from the side over the one it covers; going back plays that in reverse. A link in a layout's own markup, such as a tab bar, crossfades instead, and so does a replace. People who ask their system for reduced motion get a short crossfade with no movement. On iOS and Android these will be the platform's own transitions (decision 0032).
Titles
The screen in front sets the document title: <screen title="Feed">, or an expression the title follows, <screen title={Post ${id}}>. Static routes also have their title in their HTML, for link previews and the first paint.
Not found
pages/_not-found.duo is shown, inside the root layout, for any path no page serves. route() works there (let { path } = route()). Without one, a plain message is shown.
Guards
A page or layout can require a condition before it is shown:
// pages/account.duo
import { guard, state } from "@duolith/client";
let signedIn = state(false, { shared: "signed-in" });
guard(() => signedIn || "/sign-in?next=/account");
- A string redirects there, replacing the screen, so back does not return to the guarded one.
true(or anything truthy) lets the screen show.false,nullorundefinedshows the not-found screen in its place.
The guard is asked before the screen is shown, again whenever the state it read changes while the screen is in front, and again when back brings a kept screen to the front: turning signedIn off on the account screen, or on any screen before going back to it, sends you to sign in. Guards that keep redirecting stop after ten, at the not-found screen. A guard in a layout protects every screen inside it.
A guard runs on the device. It decides what the app shows; it does not protect data, which only the server that holds it can do.
Shared state
state(initial, { shared: "name" }) gives every screen that declares state with the same name one value, for as long as the app runs. Above, the sign-in screen and the account screen both declare signed-in, so turning it on in one is seen by the other. Use it for app-wide facts such as the signed-in user or settings; keep everything else in the screen's own state.
Building and deploying
There is no server, so duolith build emits one app: index.html and a copy of it for each route without parameters (search/index.html, profile/settings/index.html, …), each with its own title and styles so a shared link paints at once, plus 404.html, the same app for every other path, and one module per page and layout under _duolith/, loaded the first time a screen needs it.
A static host must answer a path it has no file for, such as /post/7, with 404.html:
- GitHub Pages, Cloudflare Pages, Surge, Render static sites: done; they serve
404.htmlfor unknown paths. - Netlify: add
_redirectswith/* /404.html 200. - Vercel: add
vercel.jsonwith{ "rewrites": [{ "source": "/(.*)", "destination": "/404.html" }] }. - nginx:
try_files $uri $uri/index.html /404.html;.
The app must be served from the root of its domain for now. duolith dev serves 404.html the same way, and its live reload keeps you on the current route.