Routing

Type-safe routes with parameters, middleware for auth guards, and nested layouts.

Defining routes

Routes are objects — not strings scattered across your codebase:

object Nav {
    val home = Static("/")
    val about = Static("/about")
    val userProfile = Route1("/users/{id}")
    val userPost = Route2("/users/{id}/posts/{postId}")
}

Static is for routes with no parameters. Route1 through Route7 support 1-7 typed parameters.

Setting up the router

val app = kraftApp {
    routing {
        usePathStrategy()  // Clean URLs: /users/123
        // or useHashStrategy() for hash URLs: /#/users/123

        mount(Nav.home) { HomePage() }
        mount(Nav.about) { AboutPage() }

        mount(Nav.userProfile) { route ->
            val userId = route["id"]
            UserProfilePage(userId)
        }

        catchAll { NotFoundPage() }
    }
}

The catchAll block handles any URL that doesn't match a defined route.

Rendering the current route

Drop RouterComponent() wherever you want the active page to appear:

class App(ctx: NoProps) : PureComponent(ctx) {
    override fun VDom.render() {
        NavBar()
        div(classes = "content") {
            RouterComponent()  // Active page renders here
        }
        Footer()
    }
}

Navigation

Programmatic navigation

// Navigate to a static route
router.navToUri(Nav.about())

// Navigate with parameters
router.navToUri(Nav.userProfile("alice"))

// Navigate handling a click event
ui.button {
    onClick { evt -> router.navToUri(evt, Nav.home()) }
    +"Go home"
}
// When you pass the MouseEvent, Kraft detects modifier keys:
// Ctrl+Click (Cmd+Click on Mac) opens in a new tab,
// just like a native link. No platform-specific code needed.

// Go back
router.navBack()

// Replace current URL (no history entry)
router.replaceUri(Nav.home())

Link-style navigation with A.href(route)

For anchor tags, use the href helper on A — it takes a bound route and writes the correct URL into the href attribute:

ui.menu {
    noui.item A { href(Nav.home()); +"Home" }
    noui.item A { href(Nav.about()); +"About" }
    noui.item A { href(Nav.userProfile("alice")); +"Alice" }
}
Always use A.href(route) for links — don't hand-write href = "/about". The helper asks the active router to render the URL using the configured path strategy, so the same code produces /about under usePathStrategy() and #/about under useHashStrategy(). Hard-coded href strings bypass the strategy and break when you switch modes (or when the app is mounted under a non-root base path).

The helper lives in io.peekandpoke.kraft.routing:

/** Sets the href attribute of an anchor tag from a bound route. */
fun A.href(route: Route.Bound) {
    val c = consumer as? VDomTagConsumer ?: error("Consumer must be a VDomTagConsumer")
    val router = c.host.router

    href = router.strategy.render(route)
}

Because it sets a real href, a plain click is routed in-app and the browser keeps Ctrl/Cmd+Click, middle-click, "Open in new tab" and link previews. No onClick is needed — adding one that calls router.navToUri makes the click navigate twice. Link Clicks lists which links and clicks the router handles.

Layouts

Wrap groups of routes in a shared layout:

routing {
    layout({ content ->
        div(classes = "app-shell") {
            NavBar()
            div(classes = "main") {
                Sidebar()
                div(classes = "content") { content() }
            }
            Footer()
        }
    }) {
        mount(Nav.home) { HomePage() }
        mount(Nav.about) { AboutPage() }
        mount(Nav.userProfile) { route -> UserProfilePage(route["id"]) }
    }
}

The layout receives a content function — call it where you want the page to render. You can nest layouts too.

Middleware

Middleware intercepts navigation before a page renders. The most common use case: auth guards.

routing {
    // Public routes
    mount(Nav.login) { LoginPage() }

    // Protected routes
    middleware({ ctx ->
        if (AppState.auth.isLoggedIn) {
            RouterMiddlewareResult.Proceed
        } else {
            ctx.redirect(router.strategy.render(Nav.login()))
        }
    }) {
        layout({ LoggedInLayout(it) }) {
            mount(Nav.dashboard) { DashboardPage() }
            mount(Nav.profile) { ProfilePage() }
        }
    }

    catchAll { NotFoundPage() }
}

Middleware returns one of:

  • RouterMiddlewareResult.Proceed — allow navigation
  • RouterMiddlewareResult.Redirect(uri) — redirect to another route

Reacting to route changes

Subscribe to the router's current stream from any component:

class BreadCrumb(ctx: NoProps) : PureComponent(ctx) {
    private val currentRoute by subscribingTo(router.current)

    override fun VDom.render() {
        ui.breadcrumb {
            div(classes = "section") { +"Home" }
            div(classes = "divider") { +"/" }
            div(classes = "active section") {
                +currentRoute.uri
            }
        }
    }
}

Guarding a page against leaving

A page with unsaved work asks before the router leaves it. guardLeaving registers while the component is mounted; its block is asked before each navigation away (navToUri, an intercepted link, replaceUri, Back and Forward, a typed hash) and decides by the state at that moment:

class LookEditor(ctx: NoProps) : PureComponent(ctx) {
    private var draft by value(Draft.empty)

    init {
        guardLeaving(beforeUnload = true) { target ->
            if (!draft.isDirty) LeaveResult.Proceed
            else LeaveResult.Ask {
                val answer = modals.showAndAwait { handle ->
                    OkCancelModal { mini(handle = handle, header = { +"Leave without applying?" }, content = {}) }
                }
                answer == OkCancelModal.Result.Ok
            }
        }
    }
}
  • Proceed leaves, Stop stays, Ask stays until its block answers: true goes on to the target. Navigations away while asking are dropped; a query-only change meanwhile keeps the question.
  • Leaving means another path (before ? and #), exactly when RouterComponent remounts the page. A change of query or fragment alone never asks, so urlParam filters do not.
  • Use it inside the routed page: it binds to the page the router is on when its component mounts.
  • A held Back, Forward or typed hash (hash routing) is undone: the router puts the page's address back as a new entry.
  • A page load is not the router's: reload, tab close, a typed address under path routing, an external link, a Back out of the app. beforeUnload = true arms the browser's own prompt for those while the block does not proceed (there the block gets null as the target, and an Ask cannot run).
  • A confirmed Ask on a Back replays the Back. A middleware redirect on the way is not asked again.
  • A leave that must happen whatever a page holds, like a logout: router.withoutLeaveGuards { router.navToUri("/login") }. A page load started in the block, or within 3 s after it (a logout through the server, location.href = ...), gets no beforeUnload prompt.
  • A hash typed into the address bar (hash routing) and a Forward are held too, but leave one extra history entry; a held Back drops the forward history.

Setting the page title

Kraft provides a PageTitle component:

class AboutPage(ctx: NoProps) : PureComponent(ctx) {
    override fun VDom.render() {
        PageTitle("About Us")

        ui.segment {
            // page content
        }
    }
}

Real-world example

Here's the routing setup from the funktor-demo admin app:

object Nav {
    val auth = AuthFrontendRoutes()
    val dashboard = Static("")
    val profile = Static("/profile")
}

fun RootRouterBuilder.mountNav(authState: AuthState<AdminUserModel>) {
    // Auth module mounts its own routes (login, logout, etc.)
    authState.mount(this)

    // Auth middleware protects everything below
    val authMiddleware = authState.routerMiddleWare(Nav.auth.login())

    middleware(authMiddleware) {
        layout({ LoggedInLayout(it) }) {
            mount(Nav.dashboard) { DashboardPage() }
            mount(Nav.profile) { ProfilePage() }
        }
    }

    catchAll { NotFoundPage() }
}

This pattern — defining routes as objects, mounting them with middleware and layouts — is how we structure all our apps.

It's a client-side SPA router. No server-side rendering, no SEO magic. If you need those, Kraft is probably not the right tool. It's built for admin panels, dashboards, and internal tools where SEO doesn't matter.