Documentation
Run rws from one config file, or build on it as a Rust crate. Start with the quick start, then pick the part you need.
Getting Started
- Quick StartFour paths to a running rust-web-server in under five minutes — static files, a first route, a config-driven proxy, and automatic HTTPS.
- ExamplesRunnable example apps in the repository — a first route, a JSON API, a static site, a reverse proxy, server-sent events, streamed uploads and MCP servers — each with its own test.
- InstallationHow to install rust-web-server as a library crate, as a standalone binary, or from source — including feature flags and MSRV.
- Dev WorkflowAutomatically rebuild and restart your rws app whenever source files change, so you're always running the latest code.
- Frontend Dev ProxyHow to run a React (or Vue/Svelte) dev server side-by-side with rws during local development, so API calls reach the backend and everything else keeps fast HMR.
- All FeaturesA complete checklist of rust-web-server capabilities organized by category, with feature flag annotations.
Configuration
- OverviewHow rust-web-server loads, layers, and hot-reloads its configuration at runtime.
- Environment VariablesComplete reference for every RWS_CONFIG_* environment variable, with defaults and descriptions.
- Config FileComplete annotated reference for every section and key in rws.config.toml.
- CLI ArgsAll command-line flags accepted by rust-web-server, with types, defaults, and examples.
Building Apps
- OverviewThree ways to add routes to rust-web-server and how a request flows from the TCP socket to your handler.
- ControllersThe Controller trait is the lowest-level way to handle HTTP requests in rust-web-server.
- RoutingPath-based routing with named parameters, wildcards, and virtual-host scoping using Router and the routes! macro.
- Request & ResponseThe Request and Response types, status code constants, MIME type constants, and how to build response bodies.
- Shared StatePass databases, caches, and config to handlers using App::with_state and Arc-wrapped types.
- Typed ExtractorsParse request bodies, query strings, and headers into typed values using FromRequest.
- Error HandlingMap Rust errors to HTTP responses using IntoResponse and the built-in AppError enum.
- MiddlewareAdd cross-cutting behaviour to any Application by implementing the Middleware trait and stacking layers with .wrap().
- ValidationValidate incoming request data with the Validate trait, the
- Forms & UploadsParse URL-encoded forms and multipart file uploads from incoming request bodies.
- JSONParse JSON request bodies and produce JSON responses with the built-in parser or the serde-backed Json<T> extractor.
- CookiesRead cookies from incoming requests, set cookies with the SetCookie builder, and sign or encrypt cookie values.
- Async HandlersWrite async route handlers using AsyncAppWithState for non-blocking I/O with databases, HTTP clients, and other async libraries.
- HTTP ClientCall external APIs from handlers with the built-in synchronous Client and the async AsyncClient.
- HTML TemplatesRender HTML responses with the Tera template engine via the tera feature flag, with hot reload for edited templates.
- Dependency InjectionUse Container to register and resolve typed services across request handlers.
Features
- CORS & SecurityConfigure cross-origin resource sharing and automatic security headers in rust-web-server.
- Static Files & ListingHow rust-web-server serves files from disk, the default directory listing page for directories without an index.html, and the opt-in SPA fallback for client-side routers.
- Rate LimitingPer-IP sliding-window rate limiting with a global singleton, per-route custom limiters, and a Redis-backed distributed limiter for multi-instance deployments.
- CompressionAutomatic brotli, zstd and gzip compression for text responses, negotiated per request, with static files compressed once.
- HTTPS / TLSServe traffic over TLS with HTTP/2 and HTTP/1.1 on the same port using rustls and aws-lc-rs.
- Automatic TLS (ACME)Get and auto-renew Let's Encrypt certificates with one config section — no certbot, no cron, no restarts.
- Mutual TLS (mTLS)Require clients to present a certificate signed by a trusted CA on every HTTPS and QUIC connection.
- Virtual HostingServe multiple domains from a single server instance, each with its own TLS certificate, using SNI-based routing.
- HTTP/2Serve HTTP/2 and HTTP/1.1 on the same TLS port with automatic ALPN negotiation, no extra configuration required.
- HTTP/3 / QUICThe default build serves HTTP/3 over QUIC on the same port number as TCP, with automatic client negotiation.
- WebSocketAdd WebSocket endpoints with RFC 6455 frame-level I/O built in — no third-party WebSocket crates required.
- Server-Sent EventsPush a stream of typed events to browser clients over a single HTTP connection with the Sse builder.
- AuthHTTP Basic Auth, HS256/RS256/ES256 JWT, and forward-auth middleware with helper functions for issuing and verifying tokens.
- OAuth2 / OIDC SSOAuthorization code flow with PKCE, session management, RS256/ES256 JWT verification via JWKS, and rws as its own OAuth 2.0 Authorization Server.
- SAML 2.0 SSOSAML 2.0 Service Provider — ACS handler, XML signature verification, and attribute mapping, for enterprise IdPs that don't speak OIDC.
- CSRF ProtectionDouble-submit cookie pattern with constant-time comparison and automatic SameSite=Strict enforcement.
- SessionsServer-side session management with in-memory, database-backed, and Redis-backed session stores.
- Email / SMTPSend transactional email from handlers using the built-in SMTP mailer — plain, STARTTLS, and SMTPS; multipart text+HTML; AUTH PLAIN.
- File / Object StorageA single Storage trait for local disk and S3-compatible object storage (AWS S3, Cloudflare R2, MinIO), with no AWS SDK dependency.
- Response CachingIn-memory, capacity-bounded response cache middleware with TTL, Vary-header support, and manual invalidation.
- MetricsBuilt-in Prometheus metrics — server-wide counters always active, per-route histograms via MetricsLayer middleware.
- Distributed TracingOpenTelemetry-compatible HTTP server spans and nested child spans via OtelLayer and otel::span, with W3C traceparent propagation.
- Hot Config ReloadUpdate proxy routes, CORS rules, rate limits, log format, TLS certificates, and Tera templates without restarting the server.
- Rewrite MiddlewareTransform requests before dispatch and responses on the way back with the RewriteLayer middleware.
- IP FilteringAllow or deny requests by client IPv4 or IPv6 address or CIDR range with the IpFilter middleware.
- Request IDGive every request/response pair a stable ID so log lines can be correlated across services.
- Background SchedulerRun background tasks on a fixed rate, fixed delay, or 6-field cron schedule without an external crate.
- Background Job QueueRun one-shot, fire-and-forget work from request handlers, with retry-with-backoff and optional crash-safe persistence.
- OpenAPI / SwaggerGenerate an OpenAPI 3.0 spec and browsable Swagger UI directly from your registered routes.
- Per-Route TimeoutsGive individual routes their own deadline instead of one global read timeout for everything.
- Typed Config BindingDerive a load() method that reads environment variables into a strongly-typed config struct at startup.
- Webhook VerificationVerify inbound webhook signatures from GitHub, Shopify, and Stripe with built-in HMAC helpers.
- Secrets Manager IntegrationResolve vault://, aws-sm://, and azkv:// secret references to their live values at startup — HashiCorp Vault, AWS Secrets Manager, and Azure Key Vault, with no vendor SDK.
Proxy / Gateway
- OverviewTwo ways to use rws as a reverse proxy — zero-code config-driven mode and programmatic library mode.
- Config-Driven ProxyFull annotated rws.config.toml reference for zero-code proxy configuration.
- Reverse ProxyHTTP/1.1 reverse proxy middleware with round-robin load balancing, path filtering, automatic failover, and built-in keep-alive connection pooling.
- Load BalancingHow rws distributes traffic across backends — round-robin everywhere, plus random, IP-hash, and least-connections in config-driven mode.
- Health ChecksAutomatic background health monitoring that removes and restores backends without restarting.
- Circuit BreakerProtect upstream services from cascading failures with a three-state circuit breaker, automatic retry middleware, and optional Redis-backed persistence.
- Canary / Traffic SplitSplit traffic proportionally across multiple backend versions with smooth weighted round-robin, live weight updates, and BackendPool-sourced groups for safe, gradual rollouts.
- Service DiscoveryKeep backend pools up to date automatically with static lists, environment variables, file polling, DNS A/SRV lookups, Consul, Docker labels, or an etcd watch stream.
- TCP ProxyForward raw TCP connections to backend servers with round-robin load balancing and no protocol overhead.
- UDP ProxyForward UDP datagrams to backend servers with round-robin load balancing for DNS, syslog, and other request-reply UDP protocols.
- WebSocket ProxyProxy WebSocket upgrade requests to backend servers and relay all frames bidirectionally with round-robin load balancing.
- gRPC ProxyRoute gRPC traffic to HTTP/2 backends — every call type streaming, status trailers kept, pooled connections, private CAs and client certificates.
Database / ORM
- OverviewAsync SQLite, PostgreSQL, and/or MySQL — even more than one at once — with a built-in connection pool via sqlx.
- #[derive(Model)]Map a Rust struct to a database table with the Model proc-macro and its field attributes.
- RepositoryAsync CRUD operations for a model type via the Repository trait and ModelRepository.
- Query BuilderUse QueryBuilder to construct typed async SELECT, COUNT, DELETE, and UPDATE queries without writing SQL.
- PaginationPaginate query results with Page<T> (offset) and CursorPage<T> (keyset), plus a built-in Link header builder.
- Raw SQLExecute hand-written SQL queries and map results to typed structs or untyped rows.
- TransactionsGroup multiple async database operations into an atomic unit that rolls back automatically on error.
- MigrationsManage schema changes with versioned SQL files that run once, are tracked in the database, and can be rolled back.
- RelationsLoad related records with async HasMany, HasOne, and BelongsTo helpers that make queries explicit and prevent hidden N+1 problems.
- In-memory SQLiteUse DbPool::memory() for zero-config isolated SQLite databases ideal for tests and prototyping.
MCP Server
- OverviewExpose tools, resources, and prompts to AI agents via the Model Context Protocol over HTTP.
- ToolsRegister callable tools that AI agents can invoke via the MCP protocol.
- ResourcesExpose readable data sources to AI agents via URI-addressed MCP resources.
- PromptsRegister reusable prompt templates on an McpServer that AI clients can invoke by name with arguments.
- AuthProtect your MCP endpoint with a static Bearer token (require_bearer) or full OAuth 2.0 / OIDC JWT verification (require_oauth).
- Operate rws from an AI clientPoint Claude Code, Claude Desktop or Cursor at a running rws and let it read metrics and logs, block an abusive IP, or switch on maintenance mode.
- Build agent tools on your appExpose an app's domain functions to AI agents as MCP tools — typed schemas, OAuth and live updates from the code the REST API already uses.
- GatewayPut one authenticated MCP endpoint in front of several MCP servers — prefixed tool names, a per-caller allow-list, and upstream credentials that never leave the gateway.
Testing
- Test ClientDispatch HTTP requests directly through your Application without opening a TCP socket.
Deployment
- DockerBuild and run rust-web-server in a minimal Docker container using multi-stage builds.
- KubernetesDeploy rust-web-server on Kubernetes with health probes, metrics scraping, graceful shutdown, and autoscaling.
- Kubernetes IngressUse KubernetesIngressWatcher and IngressRouter to dynamically route traffic from Kubernetes Ingress rules.
- ObservabilityMetrics, structured logs, distributed tracing, and health endpoints for rust-web-server.
- systemdRun rws as a hardened systemd service — from the deb/rpm packages or by hand; unprivileged user, read-only system, ports below 1024, reload and log rotation by signal.
- WindowsRun rws on Windows, in a terminal or as a Windows service started at boot and stopped gracefully by the Service Control Manager.
- WASM Guest ComponentRun rust-web-server's App/Router/middleware inside a WASM runtime (Wasmtime, Spin, Fastly Compute) via the wasi:http/proxy world.
Reference
- API ReferenceQuick-reference index of all major public types in rust-web-server, grouped by area.
- TroubleshootingCommon errors when starting, reaching, building and deploying rws, and how to fix them.
- Migrating to 18.0What changes when upgrading rws from 17.x to 18.0 — Header field types, default response headers, and RSA public keys.
- ArchitectureHow rws handles a request — listeners, the HTTP/1.1, HTTP/2 and HTTP/3 front ends, the Application trait, middleware, the static-file and proxy fast paths, and configuration.
- Benchmarksrws compared with Caddy and nginx on static files and reverse proxying, and how to reproduce the numbers.
- RoadmapPlanned features for rust-web-server — each appears as a callout on the relevant docs page.