Upgrades
What to do when a new Loco version is out?
- Create a clean branch in your code repo.
- Update the Loco version in your main
Cargo.toml - Consult with the CHANGELOG to find breaking changes and refactorings you should do (if any).
- Run
cargo loco doctorinside your project to verify that your app and environment is compatible with the new version
As always, if anything turns wrong, open an issue and ask for help.
Major Loco dependencies
Loco is built on top of great libraries. It’s wise to be mindful of their versions in new releases of Loco, and their individual changelogs.
These are the major ones:
Upgrade from 0.16.x to 1.0
1.0 is a large, intentionally-breaking release — the first stable Loco. Its headline change is the move to Sea-ORM 2.0. This section is assembled per area; start with the Sea-ORM steps, which affect every app that uses a database. Cross-check the 1.0.0 CHANGELOG for anything specific to APIs you use directly.
Toolchain: Rust 1.94+
Loco 1.0 uses Sea-ORM 2.0, whose MSRV is Rust 1.94. Update your toolchain:
rustup updateSea-ORM 2.0
Loco upgraded from Sea-ORM 1.1 to Sea-ORM 2.0. For most apps the migration is
mechanical — bump the pins and the CLI — because Loco’s schema helpers and the
generated model/migration shapes absorb the API changes for you.
1. Bump the dependency pins. In your app Cargo.toml:
# beforesea-orm = { version = "1.1", features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls", "macros"] }# aftersea-orm = { version = "2.0", features = ["sqlx-sqlite", "sqlx-postgres", "runtime-tokio-rustls", "macros"] }And in your migration/Cargo.toml:
# beforesea-orm-migration = { version = "1.1.0", features = [...] }# aftersea-orm-migration = { version = "2.0", features = [...] }If you depend on sqlx directly, bump it to 0.9.
2. Update the Sea-ORM CLI (used by cargo loco db entities) to 2.0:
cargo install sea-orm-cli --version '^2.0'cargo loco doctor will now flag a Sea-ORM or Sea-ORM CLI older than 2.0.
3. Regenerate entities (recommended). Run cargo loco db entities so your
src/models/_entities/ are produced by the 2.0 codegen.
4. Hand-written queries / migrations. If you wrote custom raw SQL or custom migrations, apply these Sea-ORM 2.0 changes (the same ones Loco itself made):
- Raw-
Statementcalls gain a_rawsuffix.db.execute(stmt)→db.execute_raw(stmt);db.query_one(stmt)/db.query_all(stmt)→query_one_raw/query_all_raw. SeaQuery statements (e.g. fromEntity::find().into_query()) are now passed by reference and need no manual.build(...):db.query_all(&select). sqlx0.9 requires runtime-built SQL strings to be wrapped inAssertSqlSafe(...):sqlx::query(AssertSqlSafe(format!(...))).- Bring
ExprTraitinto scope for expression methods:use sea_orm::ExprTrait;. ReplaceAlias::new("col")with the bare string"col". - Unsupported-backend branches should return
DbErr::BackendNotSupported { .. }rather than panic; Sea-ORM 2.0 removed the internal panics (a newDbErrvariant carries the case). If youmatchonDbErrexhaustively, add the arm. insert_manyno longer needs.on_empty_do_nothing(), andexec_with_returning_manyis nowexec_with_returning.
5. Note on Postgres auto-increment. Sea-ORM 2.0 emits
GENERATED BY DEFAULT AS IDENTITY instead of SERIAL for new
auto_increment() columns. Existing tables are unaffected; only newly generated
migrations differ. See the Sea-ORM 2.0 migration guide for the
option-postgres-use-serial escape hatch if you need the old behavior.
For the full upstream detail see the Sea-ORM 2.0 migration guide.
Generated code now uses 64-bit primary keys
Newly generated models and scaffolds now use i64 (BIGINT) primary keys and
foreign keys, and the int/unsigned field types generate 64-bit columns. This
is required by Sea-ORM 2.0 (its codegen maps SQLite integers to i64) and
matches the modern bigint-by-default convention.
This only affects code you generate after upgrading — your existing tables,
migrations, and entities are untouched. If you scaffold new resources and want
them to relate to older i32-keyed tables, make the key types match (either
widen the old ones with a migration, or hand-edit the new id/foreign-key
fields back to i32).
Multi-database: ExtraDbInitializer → MultiDbInitializer
The single-extra-connection initializer (initializers.extra_db, which layered a
bare Extension<DatabaseConnection>) was removed. Use MultiDbInitializer with a
one-entry initializers.multi_db map instead, and extract the connection with
Extension<MultiDb>:
// before: Extension<DatabaseConnection>// after:let conn = multi_db.get("<name>")?;Move whatever you configured under extra_db into a one-entry multi_db map.
AppContext is now #[non_exhaustive] — construct with the builder
Field access (ctx.db, ctx.config, State/FromRef extraction) is unchanged,
so most apps need no change. But direct struct-literal construction and exhaustive
pattern matches on AppContext from outside the framework no longer compile (this
makes future context fields non-breaking to add). If you built an AppContext by
hand — e.g. in a custom boot or test harness — use the builder:
let ctx = AppContext::builder(environment, db, config) // builder(environment, config) without `with-db` .queue_provider(queue) .mailer(mailer) .storage(storage) .build();loco_rs::Error is now #[non_exhaustive]
The framework’s Error enum is marked #[non_exhaustive] so new variants can be
added in the future without a breaking change. If you match on loco_rs::Error
(or loco_rs::prelude::Error) exhaustively, add a wildcard arm:
match err { Error::NotFound => { /* ... */ } // ...handle the variants you care about... _ => { /* fallback */ }}Most apps use Result<T> / ? and never match on Error directly, so no change
is needed.
More accurate HTTP status codes for errors
IntoResponse for Error previously collapsed most variants to 500. Now
Model(EntityNotFound) → 404, Model(EntityAlreadyExists) → 409, and model
validation / form-body rejections → 4xx (matching JSON rejections); genuinely
internal errors still return 500. This is behavior-only — no API changed — but
if your tests asserted the old 500s, update them to the corrected codes.
Background job priorities (Redis backend is breaking)
Background jobs now support a priority (higher numbers run first). You can enqueue with an explicit priority:
DownloadWorker::perform_later_with_priority(&ctx, args, Some(42)).await?;- Postgres / SQLite: no action needed. A
prioritycolumn is added to the queue table automatically on startup; existing jobs default to priority0. - Redis: breaking. To order by priority, the Redis backend now stores the queue as a Sorted Set (ZSET) instead of a List. Jobs already sitting in the old List-based queue keys will not be picked up after upgrading. Drain your Redis queues before deploying 1.0 (let workers finish in-flight jobs on the old version, or clear the queue if you can re-enqueue). Newly enqueued jobs use the ZSET format automatically.
Mailer jobs enqueue at priority 100 by default; override per mailer via
MailerOpts { priority, .. }.
perform_later returns the job id
Worker::perform_later now returns the enqueued job’s id
(Result<String> instead of Result<()>), and Queue::enqueue returns
Result<Option<String>>. Existing call sites keep working — perform_later(..) .await?; simply ignores the returned id. Capture it when you want to track
status:
let job_id = DownloadWorker::perform_later(&ctx, args).await?;Background queue is now a QueueProvider adapter
bgworker::Queue is now a newtype over Arc<dyn QueueProvider>, so backends are
pluggable. All queue methods keep the same signatures and behavior. Only two
source-level changes affect callers:
- Construct a no-op queue with
Queue::empty()instead ofQueue::None. - Code that pattern-matched the enum variants (e.g.
Queue::Postgres(pool, ..)to reach the raw pool) no longer compiles — use the provider methods instead.
PageResponse carries a meta: PagerMeta
Pagination results moved the flat total_pages / total_items fields into a
meta: PagerMeta (which also carries page and page_size):
// beforelet total = page.total_pages;// afterlet total = page.meta.total_pages; // also: page.meta.page, page.meta.page_size, page.meta.total_itemsStorage: MirrorStrategy / BackupStrategy → ReplicatedStrategy
The two strategies were the same primary-plus-secondaries replication engine and
are now one storage::strategies::replicated::ReplicatedStrategy with a single
FailurePolicy enum:
// MirrorStrategy::new(p, s, MirrorAll) ->ReplicatedStrategy::mirror(p, s, FailurePolicy::FailIfAny);// BackupStrategy::new(p, s, BackupAll) ->ReplicatedStrategy::backup(p, s, FailurePolicy::FailIfAny);Old FailureMode maps: AllowMirrorFailure / AllowBackupFailure → AllowAll,
AtLeastOneFailure → AllowSingleFailure, CountFailure(n) → FailAtFailures(n).
Former-backup secondary writes now run concurrently (were sequential); the
collected errors and failure decision are unchanged.
Storage: local driver no longer roots at / (security)
storage::drivers::local::new() previously rooted the store at /, so a key
derived from user input could escape to the whole disk (key etc/passwd read
/etc/passwd). It now roots at the current working directory. If you relied on
absolute-path keys, opt back in explicitly:
local::new_with_prefix("/your/root")Config: {env}.local.yaml now deep-merges over {env}.yaml
Previously the first existing file won and the other was ignored, so a
.local.yaml had to restate the whole config. Both files now layer with local
precedence: mappings merge recursively; scalars and sequences in local replace the
base value (sequences are not concatenated). If you kept a full-config
.local.yaml, trim it to just the keys you override — base keys now persist
unless explicitly overridden.
Fallback middleware defaults to 404
When the built-in fallback is enabled without an explicit code, it now returns
404 Not Found (matching its docs and the bundled not-found page) instead of
200 OK. If you relied on the enabled fallback returning 200, set code: 200
explicitly. The file-based fallback (ServeFile) is unaffected.
remote_ip rebuilt on axum-client-ip; trusted_proxies removed (security)
This is a silent, security-relevant change. An old config’s trusted_proxies:
key is now an unknown field and is ignored without error, so review your
remote_ip config before upgrading — it will not fail to load.
Previously the middleware walked X-Forwarded-For right-to-left, skipping any
address in a trusted_proxies CIDR list (or a built-in RFC-1918 + loopback list).
It now trusts exactly one configured source (source: ClientIpSource, default
RightmostXForwardedFor) and does no CIDR filtering.
- Single reverse-proxy deployments: unaffected.
- Multi-hop topologies (CDN → LB → ingress): configure your innermost hop to
set the client IP (e.g. nginx
set_real_ip_from/real_ip_recursive), or pointsourceat a provider header (CfConnectingIp,CloudFrontViewerAddress,XRealIp,ConnectInfo, …).
The RemoteIP extractor and its Display output are unchanged.
JWT: algorithm() restricted to the HMAC family
JWT::algorithm() now takes loco_rs::auth::jwt::JWTAlgorithm
(HS256 / HS384 / HS512) instead of jsonwebtoken::Algorithm. Asymmetric
algorithms — which could never work with Loco’s shared base64 secret and silently
produced broken tokens — are no longer representable. If you passed a
jsonwebtoken::Algorithm, switch to the matching JWTAlgorithm variant.
View engine: use TeraView::build_with_post_process
In after_routes, replace TeraView::build()?.post_process(...) with the
combined constructor:
// beforeengines::TeraView::build()?.post_process(move |tera| { tera.register_function("t", FluentLoader::new(arc.clone())); Ok(())})?// afterengines::TeraView::build_with_post_process(move |tera| { tera.register_function("t", FluentLoader::new(arc.clone())); Ok(())})?Mailer: Template::new(dir) now returns Result
Email templates render through a full Tera instance (so they support inheritance
and shared templates). Standard usage via Mailer::mail_template is unchanged; if
you called Template::new(dir) directly, add ?:
let tpl = Template::new(dir)?;Tasks: Vars::cli_arg returns Result<&str>
Vars::cli_arg now returns Result<&str> (was Result<&String>). Callers that
relied on &String (e.g. .clone() into a String) should use .to_owned().
Dependency majors
1.0 bumps several dependency majors. These are transitive for most apps — you
only need to act if you use one of these crates directly through Loco’s
public API: thiserror 1→2, tower 0.4→0.5, heck→0.5, byte-unit 4→5,
ipnetwork 0.20→0.21, strum→0.27, redis 0.31→1, bb8-redis→0.26,
opendal 0.54→0.57. serde_yaml (archived) was replaced by the maintained
serde_yaml_ng fork.
Feature-flag changes (1.0)
auth_jwt→auth.bg_redis→worker_redis;bg_pg/bg_sqlt→worker.defaultnow includesworker(Postgres+SQLite queues); addworker_redisfor a Redis queue.integration_testremoved (was dead).loco newnow offers Redis/Postgres/SQLite queue backends and (serverside) embedded assets.
Upgrade from 0.15.x to 0.16.x
Use AppContext instead of Config in init_logger in the Hooks trait
PR: #1418
If you are supplying an implementation of init_logger in your impl of the Hooks trait in order to set up your own logging, you will need to make the following change:
fn init_logger(config: &config::Config, env: &Environment) -> Result<bool> {fn init_logger(ctx: &AppContext) -> Result<bool> {Any code in your init_logger implementation that makes use of the config can access it through ctx.config. In addition, you will also be able to access anything else in the AppContext, such as the new shared_store. The env parameter is also removed, as that is accessible from the AppContext as ctx.environment.
Swap to validators builtin email validation
PR: #1359
Swap from using the loco custom email validator, to the builtin email validator from validator.
#[validate(custom (function = "validation::is_valid_email"))]#[validate(email(message = "invalid email"))]pub email: String,Job system
Two major changes have been made to the background job system:
- The Redis provider is no longer Sidekiq-compatible and uses a custom implementation
- All providers (Redis, PostgreSQL, SQLite) now support tag-based job filtering
What Changed
Removing Sidekiq Compatibility
The Redis background job system has been completely refactored, replacing the Sidekiq-compatible implementation with a new custom implementation. This provides greater flexibility and improved performance, but means:
- Jobs pushed from older Loco versions (pre-0.16) will not be recognized or processed
- The Redis data structures have changed entirely
- There is no automatic migration path for existing queued jobs
Adding Job Filtering
A new tag-based job filtering system has been added to all background worker providers:
- Workers can now specify which tags they’re interested in processing
- Jobs can be tagged when enqueued
- Workers with no tags only process untagged jobs, while tagged workers process jobs with matching tags
- The same API is used across all providers
How to Upgrade
To upgrade to the new job system:
-
Process existing jobs:
- Make sure all jobs in your queue are processed/completed before upgrading
-
Clean up old data:
- For Redis: Flush the Redis database used for jobs (
FLUSHDBcommand) - For PostgreSQL: Drop the job queue tables
- For SQLite: Delete the job queue tables
- For Redis: Flush the Redis database used for jobs (
-
Update Loco:
- Update to Loco 0.16+
- Loco will automatically create new job tables with the correct schema on first run
Generic Cache
PR: #1385
The cache API has been refactored to support storing and retrieving any serializable type, not just strings. This is a breaking change that requires updates to your code:
Breaking Changes:
- Type Parameters Required: All cache methods now require explicit type parameters
- Method Signatures: Some method signatures have changed to support generics
- Object Serialization: Any type you store must implement
SerializeandDeserializefrom serde
Migration Guide:
Before:
// Get a string value from cachelet value = cache.get("key").await?;
// Insert or get with callbacklet value = app_ctx.cache.get_or_insert("key", async { Ok("value".to_string())}).await.unwrap();
// Insert or get with expirylet value = app_ctx.cache.get_or_insert_with_expiry("key", Duration::from_secs(300), async { Ok("value".to_string())}).await.unwrap();After:
// Get a string value from cache - specify the typelet value = cache.get::<String>("key").await?;
// Direct insert with any serializable typecache.insert("key", &"value".to_string()).await?;
// Insert or get with callback - specify return typelet value = app_ctx.cache.get_or_insert::<String, _>("key", async { Ok("value".to_string())}).await.unwrap();
// Store complex types#[derive(Serialize, Deserialize)]struct User { name: String, age: u32,}
let user = app_ctx.cache.get_or_insert_with_expiry::<User, _>( "user:1", Duration::from_secs(300), async { Ok(User { name: "Alice".to_string(), age: 30 }) }).await.unwrap();Implementing for Custom Types:
For your custom types to work with the cache, ensure they implement Serialize and Deserialize:
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]struct MyType { // fields...}Authentication Error Handling
Authentication error handling has been improved to better distinguish between actual authorization failures and system errors:
- System errors now return 500: Database errors during authentication now return Internal Server Error (500) instead of Unauthorized (401)
- Improved error logging: Authentication errors are now logged with detailed messages using
tracing::error - Message changes: Generic error messages have been updated from “other error: ‘{e}’” to “could not authorize”
Migration Guide:
If you have code that relies on database errors during authentication returning 401 status codes, you’ll need to update your error handling. Any code expecting a 401 for database connectivity issues should now handle 500 responses as well.
Client applications should be prepared to handle both 401 and 500 status codes during authentication failures, with 401 indicating authorization problems and 500 indicating system errors.
Server side rendering
We had some changes in Tera template. go to src/initializers/view_engine.rs and replace the after_routes function with:
async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> { let tera_engine = if std::path::Path::new(I18N_DIR).exists() { let arc = std::sync::Arc::new( ArcLoader::builder(&I18N_DIR, unic_langid::langid!("en-US")) .shared_resources(Some(&[I18N_SHARED.into()])) .customize(|bundle| bundle.set_use_isolating(false)) .build() .map_err(|e| Error::string(&e.to_string()))?, ); info!("locales loaded");
engines::TeraView::build()?.post_process(move |tera| { tera.register_function("t", FluentLoader::new(arc.clone())); Ok(()) })? } else { engines::TeraView::build()? };
Ok(router.layer(Extension(ViewEngine::from(tera_engine)))) }Upgrade from 0.14.x to 0.15.x
Upgrade validator crate
PR: #1199
Update the validator crate version in your Cargo.toml:
From
validator = { version = "0.19" }To
validator = { version = "0.20" }User claims
PR: #1159
-
Flattened (De)Serialization of Custom User Claims: The
claimsfield inUserClaimshas changed fromOption<Value>toMap<String, Value>. -
Mandatory Map Value in
generate_tokenfunction: When callinggenerate_token, theMap<String, Value>argument is now required. If you are not using custom claims, pass an empty map (serde_json::Map::new()). -
Updated generate_token Signature: The
generate_tokenfunction now takesexpirationas a value instead of a reference.
Pagination Response
PR: #1197
The pagination response now includes the total_items field, providing the total number of items available.
{"results":[],"pagination":{"page":0,"page_size":0,"total_pages":0,"total_items":0}}Explicit id in migrations
PR: #1268
Migrations using create_table now require ("id", ColType::PkAuto), new migrations will have this field automatically added.
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { create_table(m, "movies", &[ ("id", ColType::PkAuto), ("title", ColType::StringNull), ], &[ ("user", ""), ] ).await }Upgrade from 0.13.x to 0.14.x
Upgrading from Axum 0.7 to 0.8
PR: #1130 The upgrade to Axum 0.8 introduces a breaking change. For more details, refer to the announcement.
Steps to Upgrade
- In your
Cargo.toml, update the Axum version from0.7.5to0.8.1. - Replace use
axum::async_trait; with useasync_trait::async_trait;. For more information, see here. - The URL parameter syntax has changed. Refer to this section for the updated syntax. The new path parameter format is:
The path parameter syntax has changed from
/:singleand/*manyto/{single}and/{*many}.
Extending the boot Function Hook
PR: #1143
The boot hook function now accepts an additional Config parameter. The function signature has changed from:
From
async fn boot(mode: StartMode, environment: &Environment) -> Result<BootResult> { create_app::<Self, Migrator>(mode, environment).await}To:
async fn boot(mode: StartMode, environment: &Environment, config: Config) -> Result<BootResult> { create_app::<Self, Migrator>(mode, environment, config).await}Make sure to import the Config type as needed.
Upgrade validator crate
PR: #993
Update the validator crate version in your Cargo.toml:
From
validator = { version = "0.18" }To
validator = { version = "0.19" }Extend truncate and seed hooks
PR: #1158
The truncate and seed functions now receive AppContext instead of DatabaseConnection as their argument.
From
async fn truncate(db: &DatabaseConnection) -> Result<()> {}async fn seed(db: &DatabaseConnection, base: &Path) -> Result<()> {}To
async fn truncate(ctx: &AppContext) -> Result<()> {}async fn seed(_ctx: &AppContext, base: &Path) -> Result<()> {}Impact on Testing:
Testing code involving the seed function must also be updated accordingly.
from:
async fn load_page() { request::<App, _, _>(|request, ctx| async move { seed::<App>(&ctx.db).await.unwrap(); ... }) .await;}to
async fn load_page() { request::<App, _, _>(|request, ctx| async move { seed::<App>(&ctx).await.unwrap(); ... }) .await;}