Routing
<RouterLink>, <RouterView> and useRoute() on the server.
A link renders differently when it points where the reader already is: it gets aria-current="page" and the router-link-active and router-link-exact-active classes. Deciding that means resolving the link as the client's vue-router will, so Router is vue-router's own matching algorithm, held to vectors recorded from the real vue-router.
The router is the ferrovue-router crate, which ferrovue holds as its module ferrovue::router with the router feature. The feature is on by default; generated code needs it once the project configures routes.
Configuring the routes
List the routes in a JSON file, the same file the client can import to build its router, and name it in ferrovue.config.json:
[
{ "path": "/", "name": "home" },
{ "path": "/blog/:slug", "name": "post" },
"/users/:name",
{ "path": "/account", "name": "account", "children": [
{ "path": "", "name": "account-home" },
{ "path": "orders", "name": "orders" }
] }
]{ "components": "client/components", "out": "src/generated", "routes": "client/routes.json" }Each route is a path, or { "path", "name", "children" }. Paths use the syntax ferrovue accepts: static segments, :name parameters, optional :name? parameters, and a final :name(.*). To match options passed to createRouter and createWebHistory, use router in place of routes:
{ "router": { "routes": "client/routes.json", "base": "/app/", "linkActiveClass": "active", "linkExactActiveClass": "active" } }The class names are written into the generated components; the base goes into route_table.rs.
A link's classes are vue-router's class object, { [activeClass]: isActive, [exactActiveClass]: isExactActive }, normalised as Vue normalises an object, then merged with the link's own class as mergeProps merges them. So a class name keeps the spaces written in it: with active-class=" on ", a link to where the reader is has class="on router-link-exact-active". Names that are array indices come first, so active-class="2" exact-active-class="1" gives class="1 2", and an own class equal to the link's classes is written once.
File-based routes
routes can also name a folder of pages. ferrovue then builds the routes from the files' paths as vue-router's file-based routing builds them (the plugin that was unplugin-vue-router, now vue-router/vite), and compiles every page as a component:
{ "components": "client/components", "out": "src/generated", "routes": { "pages": "client/pages" } }In router, it is "router": { "routes": { "pages": "client/pages" }, "base": "/app/" }. A folder of pages gives these routes:
| File | Route | Name |
|---|---|---|
index.vue | / | / |
about.vue | /about | /about |
books/index.vue | /books | /books/ |
books/[id].vue | /books/:id | /books/[id] |
[[lang]]/about.vue | /:lang?/about, with lang optional | /[[lang]]/about |
[...path].vue | /:path(.*), every path no other route matches | /[...path] |
(shop)/cart.vue | /cart: a group folder adds nothing to the path | /(shop)/cart |
users.vue and users/[id].vue | /users, whose <RouterView> shows /users/:id | /users, /users/[id] |
users.edit.vue | /users/edit, nested in nothing | /users.edit |
admin/_parent.vue | /admin, the layout of the pages in admin/ | none |
A route's name is vue-router's: the file's path, so a <RouterLink> writes :to="{ name: '/books/[id]', params: { id } }" and the server matches route.name() against Some("/books/[id]"). A folder with no .vue file of its own name beside it is a route with no component, which only groups the routes in it: vue-router never matches it itself, so without books/index.vue, /books matches no route (or the catch-all). The routes ferrovue builds are held to the ones vue-router's own plugin builds, recorded from it for a set of folders that uses each convention.
Each page is compiled as a component named after its path in the folder, in PascalCase: books/[id].vue is BooksId, written to books_id.rs, with its fixtures under fixtures/BooksId/. A page whose name is a component's too, or another page's (a-b.vue and a_b.vue), is refused, as is one whose name starts with a digit.
The client gets the same routes from ferrovue/routes, which the Vite plugin writes from the folder. Its routes are vue-router's records, each page loaded lazily, as vue-router/auto-routes gives them for the same folder:
import { createRouter, createWebHistory } from "vue-router";
import { routes } from "ferrovue/routes";
const router = createRouter({ history: createWebHistory(), routes });An application already using vue-router's own plugin with its default options can keep it: its records are these. A client that only hydrates the pages the server rendered imports the default export instead, the routes as a routes file lists them, and gives every page a component that renders nothing; routeRecords from ferrovue/route-records leaves a folder without one, as vue-router's plugin does:
import { createRouter, createWebHistory } from "vue-router";
import { routeRecords } from "ferrovue/route-records";
import pageRoutes from "ferrovue/routes";
const ServerPage = { render: () => null };
const router = createRouter({ history: createWebHistory(), routes: routeRecords(pageRoutes, ServerPage) });What a file name can say beyond this is refused, each with its code:
| Refused | Code |
|---|---|
routes that is neither a file nor { "pages": "…" } | FV1238 |
| A pages folder that cannot be read | FV1239 |
A parameter beside text in one part of the path (prefix-[id].vue), a repeatable parameter ([id]+), an optional catch-all ([[...path]]), a parameter parser ([id=int]), a character code ([x+2E]), a catch-all that holds other pages, and text other than letters, digits, - and _ | FV1240 |
A named view (index@aside.vue) | FV1241 |
definePage() | FV1242 |
A <route> block | FV1243 |
_parent.vue in the pages folder itself, or in a folder with no other pages | FV1244 |
| A page whose component name is taken, or starts with a digit | FV1245 |
definePage() and <route> change a page's route at build time, from code ferrovue does not run; the server's routes come from the files' paths alone.
The generated route table
// @generated by ferrovue from routes.json. Do not edit: change the routes file and run
// `ferrovue`.
//! The app's routes: what `<RouterLink>` resolves against and `useRoute()` reads.
/// Each route: its vue-router path, its name if it has one, whether it shows a component, and the
/// routes nested in it.
pub const ROUTES: &[ferrovue::router::RouteDef<'static>] = &[
ferrovue::router::RouteDef::new("/"),
ferrovue::router::RouteDef::new("/users/:name"),
];
/// Every route's full path, nested ones included.
pub const PATHS: &[&str] = &[
"/",
"/users/:name",
];
/// The history's base, which every link's `href` starts with.
pub const BASE: &str = "";
/// The router these routes make: build it once, and resolve each request's location with
/// [`ferrovue::router::Router::at`].
pub fn router() -> ferrovue::router::Router {
ferrovue::router::Router::tree(ROUTES).with_base(BASE)
}Each route is a RouteDef, built with RouteDef::new and its with_name, with_view and with_children, which are const. A route table written by hand for Router::tree is built the same way.
A router per application, a route per request
Build the Router once, at start-up, and keep it in the application's state; it is immutable and Send + Sync. For each request, resolve the location with Router::at, which takes the path with any query and hash, without the history's base, as vue-router's history reports it. The Route it returns borrows the router, and is what every component that links or reads the route takes.
A path matches a route as vue-router matches it: case-insensitively, with or without one trailing slash, unless the router is strict or case-sensitive. The route / also matches //, a location vue-router warns about and still resolves to it, so a request for // renders the home page and its links as the client will.
The server can read the same route to decide what to render:
let router = ferrovue::router::Router::named(&[("/", Some("home")), ("/books/:id", Some("book"))]);
let route = router.at("/books/dune?ref=home#reviews");
match (route.name(), route.param("id")) {
(Some("home"), _) => { /* render the home page */ }
(Some("book"), Some(id)) => assert_eq!(id, "dune"),
_ => { /* no route matched: a 404 page */ }
}
assert_eq!(route.path(), "/books/dune");
assert_eq!(route.query("ref").attr_value(), Some("home"));
assert_eq!(route.hash(), "#reviews");
assert_eq!(route.full_path(), "/books/dune?ref=home#reviews");Matching paths exactly
createRouter({ strict: true }) matches a path only without a trailing slash, and / only as /. createRouter({ sensitive: true }) matches a route's static text only in the case the route writes it. Set the same options under router in ferrovue.config.json, and route_table.rs builds the router with Router::with_strict and Router::with_sensitive:
{ "router": { "routes": "client/routes.json", "strict": true, "sensitive": true } }let router = ferrovue::router::Router::named(&[("/admin", Some("admin"))])
.with_strict(true)
.with_sensitive(true);
assert_eq!(router.at("/admin").name(), Some("admin"));
assert_eq!(router.at("/admin/").name(), None);
assert_eq!(router.at("/Admin").name(), None);Give linkRoutes the same strict and sensitive, so the client resolves the page the server rendered. The options also change the order vue-router tries routes in, and ferrovue's order follows it: with strict, /a matches the route /a before /a/:b?, and without it, /a/:b? first.
A web framework's own routes match their paths exactly. With both options set, a path that misses a route of the framework misses the same route in the router, so a page rendered from the framework's fallback is never one a guarded route of the framework serves. Routes behind middleware says more.
<RouterView>: a page in a layout
A component with <RouterView> takes the page it shows as the router_view slot of its Slots. Which page that is, is the server's decision, made from the route as above. This is the repository's examples/greeting, whole:
<!-- Layout.vue -->
<script setup lang="ts">
defineProps<{ user: string }>();
</script>
<template>
<div id="app">
<nav><RouterLink to="/">home</RouterLink> <RouterLink :to="'/users/' + user">{{ user }}</RouterLink></nav>
<main><RouterView /></main>
</div>
</template>use generated::{greeting, layout, route_table};
let router = route_table::router();
let route = router.at("/users/ada");
let greeting = greeting::Props::new("Ada", 3);
// The page the route shows: an island, which the client hydrates from its `data-props`.
let page = |out: &mut String| greeting::island(&greeting).render_to(out);
let mut html = String::new();
layout::render(
&mut html,
&layout::Props::new("ada"),
layout::Slots { router_view: ferrovue::render::Slot::new(&page) },
&route,
);
assert_eq!(
html,
concat!(
r#"<div id="app"><nav><a href="/" class="">home</a> "#,
r#"<a aria-current="page" href="/users/ada" class="router-link-active router-link-exact-active">ada</a></nav>"#,
r#"<main><div data-island="Greeting" data-props='{"name":"Ada","unread":3}'>"#,
r#"<p class="greeting">Hello, Ada!<b>3 new</b><!----></p></div></main></div>"#,
)
);How links are written
For each <RouterLink> the generated code asks the route to resolve the link and writes the result: Route::link for a string to, Route::link_named for { name, params, query, hash }, Route::link_path for { path, query, hash }. Each returns a Link: the href, with the base, and whether it is active and exactly active.
Generated code writes each link straight into the page, resolved as these methods resolve it: the anchor's href goes from the base, the path and the query and hash into the output, and the link's parameters are compared with the route's where they stand, so the link allocates nothing. A string to's parameters are read in to; a named route's are encoded as they are written, and compared as they were given. A query is built into one string first, with query_into. A router with a route of more than eight parameters matches a string or path in a vector, and a link to a named route of more than eight parameters holds them in one. A <RouterLink> that takes fallthrough attributes gets its Link from the methods above, to merge its href and classes with the attributes.
Nested routes work the same way at every level: a parent route's component has a <RouterView> whose slot holds the child route's component. A link to a parent is active, but not exactly active, on its children's pages.
A component with <style scoped> may hold <RouterLink>s, which carry its id as vue-router renders them, but not a <RouterView>, which would give the page it shows that component's id: put the <RouterView> in a component without scoped styles. See scoped_styles.
useRoute() and $route
A component that reads the route takes the Route too. Each field is a method, and route.query.x is a Query, because vue-router's query values may be absent, null, a string or an array:
| In the template | In the generated Rust |
|---|---|
route.path | Route::path |
route.fullPath | Route::full_path |
route.hash | Route::hash |
route.name | Route::name |
route.params.slug | Route::param |
route.query.q | Route::query |
A field read by a string key is the same field: route["path"] is route.path, and route.params["slug"] is route.params.slug. route.meta and route.matched are refused. An optional parameter the location leaves out is absent, as in vue-router: route.params.lang is undefined, and Route::param is None.
Links when the application navigates on its own
An application may already have a navigation layer of its own: it fetches the next page and swaps it in, with its own prefetching, page cache and scroll restoration. It can still use <RouterLink> for resolving to and for marking the link to the current page, on the server and after hydration alike, as long as vue-router never leaves the page itself. Otherwise a click pushes a route that nothing renders: the URL changes and the page does not.
linkRoutes from ferrovue/link-routes gives <RouterLink> and useRoute() the page's route with no router. It reads the same routes file the compiler reads (or, with a folder of pages, the default export of ferrovue/routes), with the base and link classes of ferrovue.config.json's router, and returns a Vue plugin, which goes in plugins:
import { mountIslands } from "ferrovue";
import islands from "ferrovue/islands";
import { linkRoutes } from "ferrovue/link-routes";
import routes from "./routes.json";
const links = linkRoutes(routes, {
navigate: (href) => navigateTheOldWay(href), // the application's own navigation
base: "/app/", // as `router.base` in ferrovue.config.json
});
await mountIslands(islands, { plugins: [links] });Components keep importing RouterLink and useRoute from vue-router. The plugin registers vue-router's own <RouterLink> and provides it, useRoute(), useRouter(), $route and $router with a small object of its own in place of a router:
- The page's route. It is resolved once, from
locationor the browser's location, with the base taken off.links.routeis the routeuseRoute()gives, a shallow reactive object as vue-router's, whichwatchandtoRefstake;useRouter().currentRouteis a ref to it. - The base of
ferrovue.config.json.baseisrouter.base, and left out there is no base, as on the server. A page's<base href>is not read, so the links hydrate as the server rendered them. - Every
toresolved as vue-router resolves it.links.resolve(to)gives what vue-router'srouter.resolve(to)gives on that page: the same ranking of routes, nested and empty-path children, optional parameters and catch-alls, case-insensitive matching, parameters decoded andhrefencoded with the base, the query parsed and written back, the hash, trailing and doubled slashes, and relative paths. A test compares it with vue-router field by field over the router vectors and random routes and locations. - Every click handed to
navigate. A link'spushorreplacecallsnavigatewith thehref, base included, and the route it resolves to, and never leaves the page: the active links keep matching the page that is on screen until the application replaces it. A click on the link to the current page is handed over too. An errornavigatethrows is logged withconsole.error, as vue-router logs a navigation error with noonErrorhandler, and rejects thepushorreplace. - The click belongs to the link.
<RouterLink>callspreventDefaulton a plain left click, so a document-level navigation listener seesdefaultPreventedand leaves that click tonavigate. A click with a modifier key, on atarget="_blank"link or already prevented is left alone, and reaches the listener, or the browser, as on any link.
What works is what <RouterLink> and useRoute() read: href with the base, the router-link-active and router-link-exact-active classes (nested routes included), aria-current="page", and useRoute()'s path, name, params, query, hash and matched. There is no router: useRouter() and $router give only what <RouterLink> reads (resolve, push, replace, options and currentRoute), $route is currentRoute.value as under vue-router, and <RouterView> is not registered, so hydrated components must not hold one. The route stays the one the plugin was built at, so when the application swaps in another page, unmount the islands and mount them again with a new linkRoutes, built at the new location.
ferrovue/link-routes imports from vue-router RouterLink and the keys it injects, which a bundler keeps apart from the rest of vue-router. Built alone as a Vite library for production (vue-router 5.4, Vue external, NODE_ENV set to production), linkRoutes is 12.4 KB minified and 4.6 KB gzipped, and linkRouter, which builds a whole vue-router, is 30.2 KB and 10.4 KB: less than half the bytes. vue-router stays an optional peer: the package root does not load it.
linkRouter from ferrovue/link-router is deprecated: it builds a vue-router whose every route renders nothing and whose every navigation after the first is handed to navigate and aborted, for the same result. It still works, and is removed in a later minor release. See moving to linkRoutes.
Panics
Router::tree panics on a path outside the syntax above or a name used twice. The generated router() builds from routes the compiler has already checked, so this happens only if the routes are edited by hand; build the router at start-up, and it happens there.