Skip to content

Shared Rust

Write validation, domain types, and encryption once in crates/shared and compile them into both your server and your app.

Introduction

The crates/shared directory is an ordinary Rust crate in your workspace. Since your server and your app are both written in Rust, anything you place in this crate compiles into both of them, with no glue code.

For example, the starter crate that init creates includes a username rule:

crates/shared/src/lib.rsrust
/// The longest username both the server and the app accept.
pub const MAX_USERNAME_LENGTH: usize = 32;

/// Whether `name` is a valid username: 3 to 32 letters, digits, `_`, or `-`.
pub fn is_valid_username(name: &str) -> bool {
    (3..=MAX_USERNAME_LENGTH).contains(&name.chars().count())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

Using It From Your Server

The init command adds crates/shared to your workspace, but nothing depends on it until you need it. To use it from your server, add it to the [dependencies] of your root Cargo.toml:

Cargo.tomltoml
[dependencies]
shared = { path = "crates/shared" }

Then your server and your app may call the same function, just as they would any other crate:

if !shared::is_valid_username(&input.username) {
    // ...
}

What to Share

Shared code works best for the rules your server and your app must agree on. For example, you might share:

  • Domain types and validation rules, so your app rejects invalid input offline using the very same rules as your server.
  • Encryption and signing helpers.
  • Local storage and sync logic for offline use.

Keeping It Portable

Since this crate also compiles for phones, you should never add laravel-rust or other server-only crates to it. If a piece of code only makes sense on one platform, you may place it behind a cfg attribute, or keep it out of the crate entirely.

Type to search…

↑↓ navigate↵ selectEsc close