What is Actix Web?
๐ฆ Powerful, pragmatic, and extremely fast web framework for Rust
Actix Web is a modern Rust web framework that delivers blazing fast performance with type safety and a rich feature set. Built on Actix actor framework, it provides everything you need for production-ready web applications.
- Type Safe - Forget stringly typed objects, from request to response everything has types
- Blazingly Fast - One of the fastest web frameworks according to TechEmpower benchmarks
- Feature Rich - HTTP/2, logging, middleware, sessions, WebSockets, and more out of the box
- Powerful Extractors - Extract data from HTTP requests with automatic deserialization and validation
- Flexible Responders - Return various types that implement the Responder trait for consistent APIs
- Easy Form Handling - Handle JSON and URL-encoded forms with automatic parsing
๐ง AstroX Backend Features
Our Actix backend implementation includes production-ready features for authentication, API endpoints, and session management.
๐ Authentication & Sessions
- Cookie-based session management with configurable domain support for subdomain sharing
-
Custom authentication middleware that protects routes using glob
patterns (e.g.,
/auth/*) - Session validation with automatic renewal to keep users logged in
-
Server-side rendered login form at
/loginwith flash message support - Protected routes automatically redirect unauthorized users with proper HTTP status codes
๐ API Endpoints
-
/api/hello- Simple JSON response endpoint demonstrating GET and POST handlers -
/api/space-x- External API proxy that fetches SpaceX rocket data from spacexdata.com -
/api/protected- Session-protected endpoint that requires authentication - All API endpoints return proper JSON responses with error handling
- Comprehensive test coverage for all endpoints using actix-web test utilities
โ๏ธ Configuration & Middleware
- CORS configuration with environment-based settings - permissive in dev, strict in production
- Command-line arguments support for host, port, environment, CORS URL, and cookie domain
- Compression middleware for optimal response sizes
- Logger middleware with configurable log levels
- URL normalization with trailing slash handling
- Static file serving with custom 404 page for SPA routing
๐งช Testing & Quality
- Unit tests for all API endpoints, middleware, and authentication logic
- Integration tests simulating full request/response cycles with sessions
- Test coverage for both authorized and unauthorized access scenarios
- Mock external API calls for reliable testing
๐ Code Examples
Protected API Endpoint
Example from src/backend/src/api/protected/get.rs - demonstrates
session validation:
#[get("/api/protected")] pub async fn protected_endpoint(session: Session) -> impl Responder { match validate_session(&session) {
Ok(_) =>
HttpResponse::Ok().json(...), Err(_) => HttpResponse::Unauthorized().json(...) }
}
Custom Authentication Middleware
From src/backend/src/auth/auth_middleware.rs - protects routes
using glob patterns:
pub struct Authentication { pub routes: Vec<String>, }
// Usage in main.rs: let auth_routes = vec!["/auth/*".to_string()];
App::new().wrap(Authentication { routes: auth_routes })
External API Proxy
From src/backend/src/api/space_x/get.rs - proxies external API
requests:
#[get("/api/space-x")] pub async fn json_get_space_x() ->
Result<HttpResponse, ActixError> { let response = get("https://api.spacexdata.com/v3/rockets").await; // Handle response and return JSON
}
CORS Configuration
From src/backend/src/cors/get_cors_options.rs - environment-based
CORS:
pub fn get_cors_options(env: String,
allowed_origin: String) -> Cors { if env == "prod" { Cors::default().allowed_origin(&allowed_origin)
} else { Cors::default().allow_any_origin()
} }
Session Validation
From src/backend/src/session/validate_session.rs - checks user
authentication:
pub fn validate_session(session: &Session)
-> anyhow::Result<()> { let user_id: Option<i64> = session.get("user_id")?; match user_id { Some(_) => { session.renew(); Ok(())
} None => Err(anyhow::anyhow!("Not authenticated"))
} }
๐ Getting Started
The Actix server starts automatically when you run the AstroX CLI. It serves both API endpoints and the built frontend.
-
Run
cargo runto start the development server with default settings -
Access the API at
http://localhost:8080/api/* -
Visit
/loginto test the server-side rendered authentication -
Configure via command-line args or
Astrox.tomlfile -
Run tests with
cargo testfor comprehensive coverage - Check out WebSockets implementation of this template in my scrum poker application at https://scrumpoker.spaceout.pl/, github repository at https://github.com/MassivDash/scrumpoker