Full-Stack Architecture in Rust: Structuring Leptos Applications Without Losing Your Mind

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

If you come from the React, Next.js, or Go ecosystem, you know that keeping the frontend and backend in sync is one of the biggest sources of bugs. Rust, powered by the Leptos framework, offers an appealing alternative: true isomorphism. One single language, shared types, and a single centralized source of truth for your system’s data and business rules.

This philosophy is familiar to those of us with a background in C#, where sharing model libraries between server and client has long been standard practice to maintain data consistency. Leptos, however, applies this approach remarkably naturally to modern web development, compiling that single source of truth both into the native server binary and into the browser’s WebAssembly.

The result is a model where contracts between frontend and backend are expressed directly in shared code, reducing the need for external schema definitions and eliminating bugs caused by misalignment across layers.

In this article, we will examine how to structure a full-stack Leptos application using a clean architecture designed for scalability and maintainability, illustrated through a practical example intended to introduce the framework’s core concepts.

1. The Heart: The Domain Layer (/domain)

In Leptos, the domain layer can be isomorphic. This means the code inside this directory compiles for both the native server target and the client WebAssembly target.

Here we define our structs and enums. By leveraging the validator crate, we can express business rules in a single place:

// domain/user.rs
#[derive(Serialize, Deserialize, Validate)]
pub struct LoginCredentials {
    #[validate(length(min = 3, message = "Usuario debe tener al menos 3 caracteres"))]
    pub username: String,
    #[validate(length(min = 6, message = "Contraseña debe tener al menos 6 caracteres"))]
    pub password: String,
}

Why is this critical?

Because the exact same validation executes on the frontend before dispatching the request—preventing unnecessary round trips—and runs again on the backend as an authoritative final check. This drastically cuts down on duplicated validation rules across layers and maintains strict model consistency.

It does not eliminate all layer-specific logic (such as UI error presentation), but it does centralize the core rule definitions.

Strongly Typed Global State

Beyond validations, the domain layer explicitly defines authentication state:

// domain/state.rs
pub enum AuthState {
    Loading,
    Authenticated(User),
    Unauthenticated,
}

This enum prevents invalid states. You cannot represent an authenticated user without actual user data, nor can you forget to handle the loading state. The Rust compiler forces exhaustiveness, eliminating a common class of bugs as your application grows.

2. The Fortress: The Server Layer (/server)

This is where sensitive operations live: database connections (SQLite/SQLx), password hashing (bcrypt), and session management.

Thanks to Leptos’s Server Functions, there is no need to write a manual REST API. You define a function, and Leptos handles the RPC transport layer between client and server under the hood:

#[server(Login, "/api")]
pub async fn login(credentials: LoginCredentials) -> Result<User, ServerFnError> {
    // Validación en servidor (misma lógica que el cliente)
    validate(&credentials)?;
    
    // Consulta a la base de datos
    let user = sqlx::query_as("SELECT * FROM users WHERE username = ?")
        .bind(&credentials.username)
        .fetch_optional(pool)
        .await?;
    
    // Verificación con bcrypt
    bcrypt::verify(&credentials.password, &user.password_hash)?;
    
    // Creación de sesión con UUID
    let session_id = Uuid::new_v4().to_string();
    
    // Cookie HttpOnly con SameSite=Lax
    let cookie = Cookie::build((SESSION_COOKIE_NAME, session_id))
        .http_only(true)
        .same_site(SameSite::Lax)
        .max_age(Duration::days(7))
        .build();
    
    Ok(user)
}

This example is intentionally simplified to illustrate the overall flow. Details such as persistent session stores, fine-grained error mapping, and additional security defenses are omitted to keep the focus on architecture and the Leptos mental model.

Secure by Default

By using the #[cfg(feature = "ssr")] directive, server-side code is only compiled when the application runs in SSR mode. Sensitive logic and backend dependencies are never bundled into the WebAssembly payload served to the browser.

Furthermore, the session management setup uses:

  • HttpOnly Cookies: Inaccessible to client-side JavaScript
  • SameSite=Lax: Baseline defense against CSRF attacks
  • Automatic Expiration: Sessions carry an explicitly defined lifespan

3. The Interface: Modular Frontend (/frontend)

To prevent the UI from becoming an unwieldy collection of files, the frontend is organized by feature rather than generic technical roles:

frontend/
├── auth/
├── users/
├── layouts/
└── state/

This layout scales comfortably with project growth and gives each module clear boundaries—essential once a codebase expands.

Global State with Signals

Authentication state is managed through a Context Provider that wraps the application:

#[component]
pub fn AuthProvider(children: Children) -> impl IntoView {
    let state = RwSignal::new(AuthState::Loading);
    
    let login_action = Action::new(|credentials| async {
        login(credentials).await
    });
    
    // Efecto reactivo: cuando login_action cambia, actualiza el estado
    Effect::new(move |_| {
        if let Some(Ok(user)) = login_action.value().get() {
            state.set(AuthState::Authenticated(user));
        }
    });
    
    provide_context(AuthContext { state, login_action });
    children()
}

Any component can read or update this state with use_auth(), completely bypassing prop drilling.

4. The Request Workflow

One of Leptos’s most powerful capabilities is its fine-grained reactivity. Rather than re-rendering entire component trees, the runtime directly updates the individual DOM nodes tied to a specific signal.

Example: Login Lifecycle

  1. User submits the LoginForm
  • Client-side validation runs with validator
  • Instant feedback is shown on failure
  1. A Leptos Action invokes the Server Function
  • Payload is serialized automatically
  • An HTTP POST request is sent to /api/login
  1. The server processes the request
  • Queries SQLite via sqlx
  • Validates the password hash with bcrypt
  • Generates the session and sets the cookie
  1. The UI reacts by updating global state
  • An Effect observes the resolved action
  • AuthState is updated
  • Dependent components reflect the changes automatically

Comparing Approaches: React/Next.js vs. Leptos

AspectReact / Next.jsLeptos
ValidationFrequently duplicated across layersSingle shared, reusable definition
Type SafetyTypeScript (type-erased at runtime)Rust (enforced at compile time)
Re-rendersComponent-level reconciliationTargeted per dependent DOM node
FE/BE IntegrationImplicit contracts, manual schemasNative shared types
Integration BugsCaught at runtimeCaught during compilation

This is not an argument that one model is unconditionally superior to another. Rather, Leptos systematically eliminates a specific class of problems inherent to frontend-backend boundaries.

5. Feature Flags: One Binary, Two Execution Targets

The project’s Cargo.toml defines two complementary feature configurations:

[features]
ssr = [
    "dep:axum",
    "dep:sqlx",
    "dep:bcrypt",
    # ... dependencias del servidor
]
hydrate = [
    "dep:wasm-bindgen",
    "dep:console_error_panic_hook",
    # ... dependencias del cliente
]

When running cargo leptos watch:

  • The server compiles with --features ssr
  • The client compiles with --features hydrate

This guarantees a clean operational boundary between client and server without requiring duplicate models or codebases.

Is Rust Ready for Full-Stack Web?

Adopting Rust and Leptos is not merely a performance decision; it is a shift in your mental model. The compiler functions as an active safety net, intercepting cross-layer inconsistencies before code ever reaches production.

The Domain–Server–Frontend architecture shown here is not meant for trivial “Hello World” projects, but it establishes a robust foundation for building maintainable full-stack systems with Rust while mitigating common integration failures.

I wrote this short guide to introduce the concept. Rather than handling every edge case, the goal is to demonstrate why this paradigm is compelling and how to approach full-stack application design in Rust. If you want to explore the implementation further, you can check out the source code repository on GitHub.

Keep coding.