Ruts: Rust Tower Session for HTTP Applications
Installation
Add the following to your Cargo.toml:
[]
= "0.6.5"
Quick Start
Here's a basic example with Axum and the RedisStore. This requires the features axum(enabled by default) and redis-store to be enabled.
use ;
use ;
use RedisStore;
use Client;
use Arc;
use ClientLike;
use CookieManagerLayer;
async
async
Session Management
Basic Operations
use Session;
use SessionMap;
use MemoryStore;
;
async
Stores
Redis
A Redis-backed session store.
Requirements
- The
redis-storefeature. - Redis 7.4 or later (required for field-level expiration using HEXPIRE)
- For Redis < 7.4, field-level expiration will not be available
use RedisStore;
let store = new;
Postgres
A Postgres-backed session store implementation.
Requirements
- The
postgres-storefeature.
use PostgresStoreBuilder;
// 1. Set up your database connection pool.
let database_url = var
.expect;
let pool = connect.await.unwrap;
// 2. Create the session store using the builder.
// This will also run a migration to create the `sessions` table.
let store = new
// Optionally, you can customize the schema and table name
// .schema_name("my_app")
// .table_name("user_sessions")
.build
.await
.unwrap;
LayeredStore
A composite store that layers a fast, ephemeral "hot" cache (like Redis) on top of a slower, persistent "cold" store (like Postgres). It is designed for scenarios where sessions can have long lifespans but should only occupy expensive cache memory when actively being used thus balancing performance and durability.
Fine-Grained Write Control
The default write-through behavior can be overridden on a per-call basis using the LayeredWriteStrategy. This gives you precise control over how your data is store.
use LayeredWriteStrategy;
use Session;
use RedisStore;
use PostgresStore;
use LayeredStore;
type MySession = ;
async
Serialization
Ruts supports two serialization backends for session data storage:
bincode(default) - Fast, compact binary serialization.messagepack- Cross-language compatible serialization
To use MessagePack instead of the default bincode, add this to your Cargo.toml:
[]
= { = "0.6.5", = false, = ["axum", "messagepack"] }
Cookie Configuration
let cookie_options = build
.name
.http_only
.same_site
.secure
.max_age // 2 hours
.path
.domain;
Important Notes
Middleware Ordering
The SessionLayer must be applied before the CookieManagerLayer:
app.layer // First: SessionLayer
.layer; // Then CookieManagerLayer
Best Practices
- Enable HTTPS in production (set
secure: truein cookie options) - Use appropriate
SameSitecookie settings - Add session expiration
- Regularly regenerate session IDs
- Enable HTTP Only mode in production (set
http_only: true)
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.
License
This project is licensed under the MIT License - see the LICENSE file for details.