Build protected routes in Rust

Gate account screens from an already-resolved session state, keep private UI out of pending and denied routes, and preserve a safe return path.
Web

What you will build

Route signed-out, pending and authenticated users to the right account screen
Separate public pages from private content
Preserve a safe return path through sign-in
Keep account data out of pending and denied route trees
An account page needs more than a condition around its final output. Constructing a private component can register resources and reducers before anything becomes visible. If access is still unresolved, hiding that component afterwards is already too late for the construction boundary.
Here, one selector maps the application's session state to a route decision, and ProtectedRoute constructs only the selected branch. Pending access builds the loading screen; signed-out access redirects to sign-in; allowed access constructs the account component. This tutorial teaches that boundary, not credential verification or session creation.
The preview buttons set sample state so you can inspect each route branch; they do not authenticate anyone. In a real app, connect SessionState to your own authentication flow. A protected UI route is not server authorisation: the server or service that reads private data must authenticate and authorise every request. See Server security for the server-side contract.
Install the Fission CLI and scaffold a Web project for the interactive preview:
cargo install cargo-fission
fission init harbour-account
cd harbour-account
cargo add serde_yaml
fission add-target web --project-dir .
Start from a new project (optional)

Project layout

harbour-account/
├── Cargo.toml                 # generated dependencies
├── fission.toml               # app identity, targets and capabilities
├── src/
│   ├── main.rs                # generated native entrypoint
│   ├── lib.rs                 # thin target launchers
│   ├── app.rs                 # native Router composition
│   ├── state.rs               # session state and one route selector
│   ├── translations.rs        # embedded locale bundles
│   └── screens/               # named route components
├── i18n/
│   ├── en-US.yaml
│   └── es-ES.yaml
├── platforms/                  # generated host files after add-target
└── tests/                      # project-specific flow checks
fission init generates Cargo.toml, fission.toml, src/main.rs, src/lib.rs, and src/app.rs. Add the feature modules as you build it. Keep data shared across routes in GlobalState; keep a view-only choice or draft in the component that owns it. If your app resolves access asynchronously, start that work through a reducer effect, job, or service—not while the component view is being built.
Replace the generated src/lib.rs at each stage so a normal launch runs the tutorial app. Its initial session is explicitly signed out because this example has no session resolver. In a connected app, remove that initialisation and hydrate the session through a startup action, leaving it Loading until the effect completes. Do not fabricate an authenticated user to make the account route appear to work.
preview/lib.rs is the documentation harness. It compiles the same component into WebAssembly so you can try the UI while reading. Its buttons set synthetic session states so you can inspect each route branch; they do not authenticate a visitor or load a real session.
Keep UI copy in English and Spanish bundles. The Web app chooses its locale when it creates the environment; the browser preview uses English. If you later add an in-app language switch, store that choice in GlobalState and mirror it into Env with with_sync_env(...).

Run the finished example

fission run --target web --project-dir .

1. Separate public pages from private content

Start with a public entry screen. It can explain what the account area contains, but it must not render account data while access is unresolved. The sign-in route in this tutorial is a placeholder; credential verification and session creation belong to your app's authentication flow.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/translations.rs","value":"src-translations-rs"},{"index":2,"label":"src/screens/mod.rs","value":"src-screens-mod-rs"},{"index":3,"label":"src/screens/public_account_entry.rs","value":"src-screens-public-account-entry-rs"},{"index":4,"label":"src/lib.rs","value":"src-lib-rs"},{"index":5,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":6,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":7,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
pub use crate::screens::PublicAccountEntry;
{"id":"fission-tabs-1","index":1,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;

pub fn create_env(locale: &str) -> Env {
    let mut env = Env::default();
    env.locale = Locale::from(locale);
    for (bundle_locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid account-route translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(bundle_locale),
            messages,
        });
    }
    env
}
{"id":"fission-tabs-1","index":2,"label":"src/screens/mod.rs","value":"src-screens-mod-rs"}
mod public_account_entry;
pub use public_account_entry::PublicAccountEntry;
{"id":"fission-tabs-1","index":3,"label":"src/screens/public_account_entry.rs","value":"src-screens-public-account-entry-rs"}
use fission::prelude::*;

fission_component! {
    pub PublicAccountEntry<()>
    view(_entry, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SemanticsRegion(
        identifier: Some("harbour-public-account-entry".to_string()),
        label: Some(cx.tr("public.semantics")),
        child: Container(Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("public.title"))
                .size(tokens.typography.heading1_size)
                .weight(tokens.typography.font_weight_bold),
            Text(cx.tr("public.body"))
                .color(tokens.colors.text_secondary),
            Text(cx.tr("public.note"))
                .color(tokens.colors.text_secondary),
            Text(cx.tr("public.signin_hint"))
                .color(tokens.colors.text_secondary),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface)
            .border(tokens.colors.border, 1.0)
            .border_radius(tokens.radii.large),
    )
}
{"id":"fission-tabs-1","index":4,"label":"src/lib.rs","value":"src-lib-rs"}
mod app;
mod screens;
mod translations;

use fission::prelude::*;

#[cfg(not(target_arch = "wasm32"))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<(), _>::new(app::PublicAccountEntry)
        .with_env(translations::create_env("en-US"))
        .run()
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<(), _>::new(app::PublicAccountEntry)
        .with_env(translations::create_env("en-US"))
        .with_title("Harbour account")
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":5,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
public.title: "Harbour Supply"
public.body: "Your shift, service requests and account details are available after sign-in."
public.note: "This page is public. Account information belongs inside the protected route."
public.signin_hint: "The sign-in route is added in the next step."
public.semantics: "Harbour Supply account entry"
signin.title: "Sign in to Harbour Supply"
signin.body: "This tutorial shows the route only. Connect sign-in to your application's authentication service."
signin.return: "Return to the public account page"
account.loading.label: "Account access is pending"
account.loading.body: "Your account details stay hidden until the application resolves access."
account.denied.label: "Account details are unavailable"
account.denied.title: "Account details aren't available."
account.denied.body: "No account details were loaded. Try again or contact your administrator."
account.private.label: "Private Harbour Supply account"
account.private.title: "Harbour Supply account"
account.welcome: "Welcome"
account.private.body: "Your open service requests and shift details are available here."
preview.title: "Route branches · sample state only"
preview.note: "These controls change local preview state. They do not authenticate a visitor."
preview.allow: "Preview authenticated state"
preview.signed_out: "Preview signed-out session"
preview.unavailable: "Preview unavailable session"
{"id":"fission-tabs-1","index":6,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
public.title: "Suministros Harbour"
public.body: "Tu turno, las solicitudes de servicio y los datos de la cuenta están disponibles al iniciar sesión."
public.note: "Esta página es pública. La información de la cuenta solo aparece en la ruta protegida."
public.signin_hint: "La ruta de acceso se añade en el siguiente paso."
public.semantics: "Acceso a la cuenta de Suministros Harbour"
signin.title: "Inicia sesión en Suministros Harbour"
signin.body: "Este tutorial solo muestra la ruta. Conecta el inicio de sesión al servicio de autenticación de tu aplicación."
signin.return: "Volver a la página pública de la cuenta"
account.loading.label: "El acceso a la cuenta está pendiente"
account.loading.body: "Los datos de la cuenta permanecen ocultos hasta que la aplicación resuelva el acceso."
account.denied.label: "Los datos de la cuenta no están disponibles"
account.denied.title: "Los datos de la cuenta no están disponibles."
account.denied.body: "No se cargaron datos de la cuenta. Inténtalo de nuevo o contacta con tu administrador."
account.private.label: "Cuenta privada de Suministros Harbour"
account.private.title: "Cuenta de Suministros Harbour"
account.welcome: "Hola"
account.private.body: "Aquí están tus solicitudes de servicio abiertas y los detalles de tu turno."
preview.title: "Ramas de rutas · solo estado de ejemplo"
preview.note: "Estos controles cambian el estado de vista previa. No autentican a nadie."
preview.allow: "Vista previa: estado autenticado"
preview.signed_out: "Vista previa: sesión cerrada"
preview.unavailable: "Vista previa: sesión no disponible"
{"id":"fission-tabs-1","index":7,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod screens;
mod translations;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<(), _>::new(app::PublicAccountEntry)
        .with_env(translations::create_env("en-US"))
        .with_title("Build protected routes in Rust")
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
Check that the first screen is public and that it does not reveal account details while access is unresolved.
Show the app preview
Hide the app preview

2. Preserve a safe return path through sign-in

Keep the session status in GlobalState and derive one route decision from it. ProtectedRoute builds only the branch that matches the state supplied by your application: a pending screen while access is unresolved, a redirect for a signed-out visitor, or the account component when the application has marked the user as authenticated.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/state.rs","value":"src-state-rs"},{"index":2,"label":"src/translations.rs","value":"src-translations-rs"},{"index":3,"label":"src/screens/mod.rs","value":"src-screens-mod-rs"},{"index":4,"label":"src/screens/public_account_entry.rs","value":"src-screens-public-account-entry-rs"},{"index":5,"label":"src/screens/sign_in_route.rs","value":"src-screens-sign-in-route-rs"},{"index":6,"label":"src/screens/session_loading_route.rs","value":"src-screens-session-loading-route-rs"},{"index":7,"label":"src/screens/account_route.rs","value":"src-screens-account-route-rs"},{"index":8,"label":"src/lib.rs","value":"src-lib-rs"},{"index":9,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
use crate::state::*;
use crate::screens::*;
use fission::prelude::*;

fission_component! {
    pub App<AppState>
    view(_app, state, cx) {
        let account_access = account_route_decision(state, &cx.view.env().current_route);
    } =>
    Router::<AppState>::new()
        .with_path(state.current_path.clone())
        .route_component(
            "/",
            PublicAccountEntry,
        )
        .route_component(
            "/account",
            ProtectedRoute::new(account_access, AccountRoute)
                .pending(SessionLoadingRoute),
        )
        .route_component("/sign-in", SignInRoute)
}
{"id":"fission-tabs-1","index":1,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SessionState {
    Loading,
    SignedOut,
    Authenticated { display_name: String },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AppState {
    pub current_path: String,
    pub session: SessionState,
}

impl Default for AppState {
    fn default() -> Self {
        Self {
            current_path: "/".to_string(),
            session: SessionState::Loading,
        }
    }
}

impl GlobalState for AppState {}

pub fn account_route_decision(
    state: &AppState,
    current_route: &fission::core::env::RouteLocation,
) -> RouteDecision {
    match &state.session {
        SessionState::Loading => RouteDecision::Pending,
        SessionState::SignedOut => RouteRedirect::replace("/sign-in")
            .return_to(current_route)
            .into(),
        SessionState::Authenticated { .. } => RouteDecision::Allow,
    }
}

pub fn route_changed(
    state: &mut AppState,
    action: fission::core::action::ShellRouteChanged,
    _cx: &mut ReducerContext<AppState>,
) {
    state.current_path = action.location.pathname;
}
{"id":"fission-tabs-1","index":2,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;

pub fn create_env(locale: &str) -> Env {
    let mut env = Env::default();
    env.locale = Locale::from(locale);
    for (bundle_locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid account-route translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(bundle_locale),
            messages,
        });
    }
    env
}
{"id":"fission-tabs-1","index":3,"label":"src/screens/mod.rs","value":"src-screens-mod-rs"}
mod public_account_entry;
pub use public_account_entry::PublicAccountEntry;
mod sign_in_route;
pub use sign_in_route::SignInRoute;
mod session_loading_route;
pub use session_loading_route::SessionLoadingRoute;
mod account_route;
pub use account_route::AccountRoute;
{"id":"fission-tabs-1","index":4,"label":"src/screens/public_account_entry.rs","value":"src-screens-public-account-entry-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub PublicAccountEntry<AppState>
    view(_entry, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SemanticsRegion(
        identifier: Some("harbour-public-account-entry".to_string()),
        label: Some(cx.tr("public.semantics")),
        child: Container(Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("public.title"))
                .size(tokens.typography.heading1_size)
                .weight(tokens.typography.font_weight_bold),
            Text(cx.tr("public.body"))
                .color(tokens.colors.text_secondary),
            Link::to(cx.tr("signin.title"), "/sign-in"),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface)
            .border(tokens.colors.border, 1.0)
            .border_radius(tokens.radii.large),
    )
}
{"id":"fission-tabs-1","index":5,"label":"src/screens/sign_in_route.rs","value":"src-screens-sign-in-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub SignInRoute<AppState>
    view(_page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    Container(Column(gap: tokens.spacing.m, children: [
        Text(cx.tr("signin.title"))
            .size(tokens.typography.heading1_size)
            .weight(tokens.typography.font_weight_bold),
        Text(cx.tr("signin.body"))
            .color(tokens.colors.text_secondary),
        Link::to(cx.tr("signin.return"), "/"),
    ]))
        .padding_all(tokens.spacing.l)
        .bg(tokens.colors.surface)
        .border(tokens.colors.border, 1.0)
        .border_radius(tokens.radii.large)
}
{"id":"fission-tabs-1","index":6,"label":"src/screens/session_loading_route.rs","value":"src-screens-session-loading-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub SessionLoadingRoute<AppState>
    view(_page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SemanticsRegion(
        identifier: Some("account-session-loading".to_string()),
        label: Some(cx.tr("account.loading.label")),
        child: Column(gap: tokens.spacing.m, children: [
            Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("account.loading.label"))),
            Text(cx.tr("account.loading.body")),
        ]),
    )
}
{"id":"fission-tabs-1","index":7,"label":"src/screens/account_route.rs","value":"src-screens-account-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub AccountRoute<AppState>
    view(_page, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let display_name = match &state.session {
            SessionState::Authenticated { display_name } => display_name.clone(),
            _ => String::new(),
        };
    } =>
    SemanticsRegion(
        identifier: Some("harbour-private-account".to_string()),
        label: Some(cx.tr("account.private.label")),
        child: Container(Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("account.private.title"))
                .size(tokens.typography.heading1_size)
                .weight(tokens.typography.font_weight_bold),
            Text(format!("{} {display_name}.", cx.tr("account.welcome"))),
            Text(cx.tr("account.private.body")),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface)
            .border(tokens.colors.border, 1.0)
            .border_radius(tokens.radii.large),
    )
}
{"id":"fission-tabs-1","index":8,"label":"src/lib.rs","value":"src-lib-rs"}
mod app;
mod screens;
mod translations;
mod state;

use fission::prelude::*;

#[cfg(not(target_arch = "wasm32"))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<state::AppState, _>::new(app::App)
        .with_env(translations::create_env("en-US"))
        .with_state_init(|state| state.session = state::SessionState::SignedOut)
        .with_route_handler(state::route_changed)
        .run()
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<state::AppState, _>::new(app::App)
        .with_env(translations::create_env("en-US"))
        .with_state_init(|state| state.session = state::SessionState::SignedOut)
        .with_route_handler(state::route_changed)
        .with_title("Harbour account")
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":9,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod screens;
mod translations;
mod state;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

fission_component! {
    pub ProtectedRoutesPreview<state::AppState>
    view(_preview, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    Column(children: [
        Container(Column(gap: tokens.spacing.s, children: [
            Text(cx.tr("preview.title")),
            Text(cx.tr("preview.note")),
            Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
                Button(
                    child: Text(cx.tr("preview.allow")),
                    key: "preview-allow",
                    on_press: reduce {
                        state.session = state::SessionState::Authenticated {
                            display_name: "Morgan Lee".to_string(),
                        };
                        cx.effects.navigate("/account");
                    },
                ).semantics_identifier("protected-routes.preview-authenticated".to_string()),
                Button(
                    child: Text(cx.tr("preview.signed_out")),
                    key: "preview-signed-out",
                    on_press: reduce {
                        state.session = state::SessionState::SignedOut;
                        cx.effects.navigate("/account");
                    },
                ).semantics_identifier("protected-routes.preview-signed-out".to_string()),
            ]),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.background),
        app::App,
    ])
}

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<state::AppState, _>::new(ProtectedRoutesPreview)
        .with_env(translations::create_env("en-US"))
        .with_route_handler(state::route_changed)
        .with_title("Build protected routes in Rust")
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
Select Preview signed-out session. The browser should leave the protected branch, show the public sign-in route, and preserve /account as a safe return path. The preview buttons are isolated in preview/lib.rs; they only set sample route state and do not implement sign-in.
Show the app preview
Hide the app preview

3. Keep unavailable access out of the account route

When your application cannot resolve access, map that result to a denied route instead of falling back to the account screen. ProtectedRoute builds the denied branch and does not construct the protected component. This example models that route decision; it does not determine whether a session is expired or valid.
The preview adds an unavailable state so you can inspect that branch. It still does not authenticate anyone. Route protection only controls the UI tree. Every server request that reads or changes account data must authenticate and authorise its caller independently. See Server security for the server-side requirements.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/state.rs","value":"src-state-rs"},{"index":2,"label":"src/translations.rs","value":"src-translations-rs"},{"index":3,"label":"src/screens/mod.rs","value":"src-screens-mod-rs"},{"index":4,"label":"src/screens/public_account_entry.rs","value":"src-screens-public-account-entry-rs"},{"index":5,"label":"src/screens/sign_in_route.rs","value":"src-screens-sign-in-route-rs"},{"index":6,"label":"src/screens/session_loading_route.rs","value":"src-screens-session-loading-route-rs"},{"index":7,"label":"src/screens/session_unavailable_route.rs","value":"src-screens-session-unavailable-route-rs"},{"index":8,"label":"src/screens/account_route.rs","value":"src-screens-account-route-rs"},{"index":9,"label":"src/lib.rs","value":"src-lib-rs"},{"index":10,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
use crate::state::*;
use crate::screens::*;
use fission::prelude::*;

fission_component! {
    pub App<AppState>
    view(_app, state, cx) {
        let account_access = account_route_decision(state, &cx.view.env().current_route);
    } =>
    Router::<AppState>::new()
        .with_path(state.current_path.clone())
        .route_component("/", PublicAccountEntry)
        .route_component(
            "/account",
            ProtectedRoute::new(account_access, AccountRoute)
                .pending(SessionLoadingRoute)
                .denied(SessionUnavailableRoute),
        )
        .route_component("/sign-in", SignInRoute)
}
{"id":"fission-tabs-1","index":1,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SessionState {
    Loading,
    SignedOut,
    Authenticated { display_name: String },
    Unavailable,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AppState {
    pub current_path: String,
    pub session: SessionState,
}

impl Default for AppState {
    fn default() -> Self {
        Self {
            current_path: "/".to_string(),
            session: SessionState::Loading,
        }
    }
}

impl GlobalState for AppState {}

pub fn account_route_decision(
    state: &AppState,
    current_route: &fission::core::env::RouteLocation,
) -> RouteDecision {
    match &state.session {
        SessionState::Loading => RouteDecision::Pending,
        SessionState::SignedOut => RouteRedirect::replace("/sign-in")
            .return_to(current_route)
            .into(),
        SessionState::Authenticated { .. } => RouteDecision::Allow,
        SessionState::Unavailable => RouteDecision::Deny,
    }
}

pub fn route_changed(
    state: &mut AppState,
    action: fission::core::action::ShellRouteChanged,
    _cx: &mut ReducerContext<AppState>,
) {
    state.current_path = action.location.pathname;
}

#[cfg(test)]
mod tests {
    use super::*;
    use fission::core::env::RouteLocation;
    #[test]
    fn pending_and_unavailable_sessions_never_allow_the_account() {
        let location = RouteLocation::new("/account");
        let mut state = AppState::default();
        assert_eq!(account_route_decision(&state, &location), RouteDecision::Pending);
        state.session = SessionState::Unavailable;
        assert_eq!(account_route_decision(&state, &location), RouteDecision::Deny);
    }
    #[test]
    fn signed_out_redirect_preserves_only_the_logical_return_route() {
        let location = RouteLocation::from_route("/account?tab=requests#open");
        let state = AppState { session: SessionState::SignedOut, ..AppState::default() };
        let RouteDecision::Redirect(redirect) = account_route_decision(&state, &location) else {
            panic!("signed-out access must redirect");
        };
        assert_eq!(redirect.history, RouteRedirectHistory::Replace);
        assert_eq!(redirect.destination,
            "/sign-in?return_to=%2Faccount%3Ftab%3Drequests%23open");
    }
}
{"id":"fission-tabs-1","index":2,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;

pub fn create_env(locale: &str) -> Env {
    let mut env = Env::default();
    env.locale = Locale::from(locale);
    for (bundle_locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid account-route translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(bundle_locale),
            messages,
        });
    }
    env
}
{"id":"fission-tabs-1","index":3,"label":"src/screens/mod.rs","value":"src-screens-mod-rs"}
mod public_account_entry;
pub use public_account_entry::PublicAccountEntry;
mod sign_in_route;
pub use sign_in_route::SignInRoute;
mod session_loading_route;
pub use session_loading_route::SessionLoadingRoute;
mod session_unavailable_route;
pub use session_unavailable_route::SessionUnavailableRoute;
mod account_route;
pub use account_route::AccountRoute;
{"id":"fission-tabs-1","index":4,"label":"src/screens/public_account_entry.rs","value":"src-screens-public-account-entry-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub PublicAccountEntry<AppState>
    view(_entry, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SemanticsRegion(
        identifier: Some("harbour-public-account-entry".to_string()),
        label: Some(cx.tr("public.semantics")),
        child: Container(Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("public.title"))
                .size(tokens.typography.heading1_size)
                .weight(tokens.typography.font_weight_bold),
            Text(cx.tr("public.body"))
                .color(tokens.colors.text_secondary),
            Link::to(cx.tr("signin.title"), "/sign-in"),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface)
            .border(tokens.colors.border, 1.0)
            .border_radius(tokens.radii.large),
    )
}
{"id":"fission-tabs-1","index":5,"label":"src/screens/sign_in_route.rs","value":"src-screens-sign-in-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub SignInRoute<AppState>
    view(_page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    Container(Column(gap: tokens.spacing.m, children: [
        Text(cx.tr("signin.title"))
            .size(tokens.typography.heading1_size)
            .weight(tokens.typography.font_weight_bold),
        Text(cx.tr("signin.body"))
            .color(tokens.colors.text_secondary),
        Link::to(cx.tr("signin.return"), "/"),
    ]))
        .padding_all(tokens.spacing.l)
        .bg(tokens.colors.surface)
        .border(tokens.colors.border, 1.0)
        .border_radius(tokens.radii.large)
}
{"id":"fission-tabs-1","index":6,"label":"src/screens/session_loading_route.rs","value":"src-screens-session-loading-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub SessionLoadingRoute<AppState>
    view(_page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SemanticsRegion(
        identifier: Some("account-session-loading".to_string()),
        label: Some(cx.tr("account.loading.label")),
        child: Column(gap: tokens.spacing.m, children: [
            Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("account.loading.label"))),
            Text(cx.tr("account.loading.body")),
        ]),
    )
}
{"id":"fission-tabs-1","index":7,"label":"src/screens/session_unavailable_route.rs","value":"src-screens-session-unavailable-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub SessionUnavailableRoute<AppState>
    view(_page, _state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SemanticsRegion(
        identifier: Some("account-session-unavailable".to_string()),
        label: Some(cx.tr("account.denied.label")),
        child: Container(Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("account.denied.title"))
                .weight(tokens.typography.font_weight_semibold),
            Text(cx.tr("account.denied.body"))
                .color(tokens.colors.text_secondary),
            Link::to(cx.tr("signin.return"), "/"),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface)
            .border(tokens.colors.border, 1.0)
            .border_radius(tokens.radii.large),
    )
}
{"id":"fission-tabs-1","index":8,"label":"src/screens/account_route.rs","value":"src-screens-account-route-rs"}
use crate::state::*;
use fission::prelude::*;

fission_component! {
    pub AccountRoute<AppState>
    view(_page, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let display_name = match &state.session {
            SessionState::Authenticated { display_name } => display_name.clone(),
            _ => String::new(),
        };
    } =>
    SemanticsRegion(
        identifier: Some("harbour-private-account".to_string()),
        label: Some(cx.tr("account.private.label")),
        child: Container(Column(gap: tokens.spacing.m, children: [
            Text(cx.tr("account.private.title"))
                .size(tokens.typography.heading1_size)
                .weight(tokens.typography.font_weight_bold),
            Text(format!("{} {display_name}.", cx.tr("account.welcome"))),
            Text(cx.tr("account.private.body")),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface)
            .border(tokens.colors.border, 1.0)
            .border_radius(tokens.radii.large),
    )
}
{"id":"fission-tabs-1","index":9,"label":"src/lib.rs","value":"src-lib-rs"}
mod app;
mod screens;
mod translations;
mod state;

use fission::prelude::*;

#[cfg(not(target_arch = "wasm32"))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<state::AppState, _>::new(app::App)
        .with_env(translations::create_env("en-US"))
        .with_state_init(|state| state.session = state::SessionState::SignedOut)
        .with_route_handler(state::route_changed)
        .run()
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<state::AppState, _>::new(app::App)
        .with_env(translations::create_env("en-US"))
        .with_state_init(|state| state.session = state::SessionState::SignedOut)
        .with_route_handler(state::route_changed)
        .with_title("Harbour account")
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":10,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod screens;
mod translations;
mod state;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

fission_component! {
    pub ProtectedRoutesPreview<state::AppState>
    view(_preview, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    Column(children: [
        Container(Column(gap: tokens.spacing.s, children: [
            Text(cx.tr("preview.title")),
            Text(cx.tr("preview.note")),
            Row(gap: tokens.spacing.s, wrap: ir_op::FlexWrap::Wrap, children: [
                Button(
                    child: Text(cx.tr("preview.allow")),
                    key: "preview-allow",
                    on_press: reduce {
                        state.session = state::SessionState::Authenticated {
                            display_name: "Morgan Lee".to_string(),
                        };
                        cx.effects.navigate("/account");
                    },
                ).semantics_identifier("protected-routes.preview-authenticated".to_string()),
                Button(
                    child: Text(cx.tr("preview.signed_out")),
                    key: "preview-signed-out",
                    on_press: reduce {
                        state.session = state::SessionState::SignedOut;
                        cx.effects.navigate("/account");
                    },
                ).semantics_identifier("protected-routes.preview-signed-out".to_string()),
                Button(
                    child: Text(cx.tr("preview.unavailable")),
                    key: "preview-unavailable",
                    on_press: reduce {
                        state.session = state::SessionState::Unavailable;
                        cx.effects.navigate("/account");
                    },
                ).semantics_identifier("protected-routes.preview-unavailable".to_string()),
            ]),
        ]))
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.background),
        app::App,
    ])
}

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<state::AppState, _>::new(ProtectedRoutesPreview)
        .with_env(translations::create_env("en-US"))
        .with_route_handler(state::route_changed)
        .with_title("Build protected routes in Rust")
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}

Run, test and build the finished project

From the project root, run the checks in order:
fission doctor --project-dir .
fission run --target web --project-dir .
cargo test
fission build --target web --project-dir .
fission test --target web --project-dir .
The route should preserve a safe return path and keep account content out of pending and denied trees. It does not replace authentication or authorization on the server.
Use these precise reference pages after the working path above is clear:
Select Preview unavailable session. The denied branch should appear without constructing the account component. This is a sample route state, not a session-verification result produced by the tutorial.
Show the app preview
Hide the app preview