The ins and outs of Rocket, in detail.

warning icon This version is a release candidate. warning icon

Upgrading

Rocket v0.6 brings many new features and improvements over Rocket v0.5, including pluggable connection listeners, Unix domain sockets, structured logging via tracing, and preview support for HTTP/3. Rocket v0.6 also includes changes that make routing more precise and remove previously deprecated APIs. While the Rust compiler can guide you through many of these changes, others require special attention. The intent of this guide is to guide you through these changes and more, migrating your Rocket application to 0.6 and reaping the benefits of new features and improvements.

This guide is not intended to replace, but instead complement, a reading of the CHANGELOG. The CHANGELOG should be considered required reading for all developers wishing to migrate their applications to Rocket v0.6.

Some changes are invisible to the compiler.

Changes to routing and the file server alter how requests are matched without causing any compiler errors. An application that compiles against v0.6 may nevertheless respond with a 404 where it previously succeeded. Read the routing section carefully and test your application's routes before deploying.

Crate Versions

Rocket v0.6 is available as a release candidate. Its crates carry -rc versions:

cratev0.5 versionv0.6 version
rocket0.5.40.6.0-rc.1
rocket_db_pools0.3.00.4.0-rc.1
rocket_dyn_templates0.3.00.4.0-rc.1
rocket_sync_db_pools0.2.00.3.0-rc.1
rocket_ws0.2.00.3.0-rc.1

Breaking changes may occur between release candidates, so a release candidate must be specified with an exact version requirement, prefixed with =. For example, to depend on the release candidates of rocket and rocket_dyn_templates, make the following changes to Cargo.toml:

1
2
3
4
5
[dependencies]
- rocket = { version = "0.5.4", features = ["json"] }
- rocket_dyn_templates = { version = "0.3.0", features = ["tera"] }
+ rocket = { version = "=0.6.0-rc.1", features = ["json"] }
+ rocket_dyn_templates = { version = "=0.4.0-rc.1", features = ["tera"] }

Rocket v0.6 and all of its contrib libraries require Rust 1.95 or later.

Default Features

Two new crate features, trace and tokio-macros, are enabled by default:

Applications that disable default features must enable these features as needed. To keep the previous defaults, enable them alongside http2:

1
2
3
4
[dependencies.rocket]
version = "=0.6.0-rc.1"
default-features = false
features = ["http2", "trace", "tokio-macros"]

The reexported tokio also no longer enables tokio's io-std feature. Applications that use rocket::tokio::io::stdin() or similar must depend on tokio directly with the io-std feature enabled.

Routing

Rocket v0.6 makes trailing slashes significant during routing. Where Rocket v0.5 disregarded a trailing slash in a request URI, Rocket v0.6 treats it as part of the URI. This affects routing in the following ways:

  1. A request URI with a trailing slash no longer matches a route URI without one, and vice versa. A request to /foo/ is not routed to /foo, and a request to /foo/?a=1 is not routed to /foo?<a>.
  2. Route URIs may end with a trailing slash: #[get("/foo/")]. Such a route only matches requests with a trailing slash.
  3. A trailing slash is an empty final segment. As such, a request to /user/ is routed to /user/<name> with an empty name. FromParam for &str, String, and numeric types fails on empty strings, so the request is forwarded with a 422 status where it previously failed to route with a 404. Parameters of type Option<T> receive None.
  4. A route with a multi-segment parameter, like /files/<path..>, no longer matches a request to /files. Requests to /files/ and below continue to match. A trailing slash is included in the matched path, so a request to /files/a/ yields a PathBuf of a/.
  5. A route with URI / mounted at a base with a trailing slash, like /foo/, only matches /foo/. Mounted at /foo, it only matches /foo. Previously, both bases matched both requests.

For example, the following two routes now match different requests:

1
2
3
4
5
#[get("/foo")]
fn foo() -> &'static str { "no slash" }

#[get("/foo/")]
fn foo_slash() -> &'static str { "slash" }

Normalizing URIs

The AdHoc::uri_normalizer() fairing recovers most of the v0.5 behavior. When attached, the fairing strips the trailing slash from any request URI that no route with a trailing slash matches. It also mounts a copy of every route like /files/<path..> at /files so that the prefix itself continues to match. The fairing logs a warning whenever it rewrites a URI.

The recommendation is to use the fairing as a stop-gap measure while updating routes and clients. Note that:

Parameters

In addition to failing on empty strings, FromParam implementations report errors with more precise types:

Routes that match on these errors must be updated. To recover the raw string when parsing fails, use Either:

1
2
3
4
5
+ use rocket::either::Either;

  #[get("/item/<id>")]
- fn item(id: Result<usize, &str>) { /* .. */ }
+ fn item(id: Either<usize, &str>) { /* .. */ }

Route Attribute

The generic route attribute now takes the route URI first and the method as an optional, named method parameter. Routes declared with route must be updated:

1
2
3
- #[route(GET, uri = "/")]
+ #[route("/", method = GET)]
  fn index() { /* .. */ }

A route without a method matches requests with any method. Any method in the IANA HTTP method registry can be named, either as an identifier like PROPFIND or as a string like "VERSION-CONTROL". The methods section of the guide has examples.

Methods

The Method enum now includes every method in the IANA HTTP method registry and is marked #[non_exhaustive]. Accordingly:

Mount Points

Mount points, or bases, are now treated like route URIs: they are never percent-decoded and are instead compared against the percent-decoded request path. Previously, a base had to be a valid origin URI.

File Server

FileServer is now built from a pipeline of rewrites that map a request to a file or redirect. FileServer::from(), the two-argument FileServer::new(), and fs::Options have been removed. All users of FileServer must:

The new FileServer::new() serves visible files from path, serves index.html for directories, and redirects requests for a directory without a trailing slash to the same URI with a trailing slash. The redirect is new: with FileServer::from(), the default in v0.5, /static/dir and /static/dir/ both served dir/index.html. Additionally, following the routing changes, a file server mounted at /static no longer serves requests to /static itself, and requests for files with a trailing slash, like /static/file.txt/, no longer succeed.

Each Options value corresponds to one or more rewrites:

v0.5 Optionsv0.6 equivalent
NoneFileServer::identity() with the filter and Prefix rewrite below
Index.rewrite(DirIndex::unconditional("index.html"))
DotFilesomit the is_visible() filter
NormalizeDirs.rewrite(TrailingDirs)
MissingPrefix::unchecked(path) in place of Prefix::checked(path)

For example, a v0.5 file server that serves dotfiles but no index files becomes:

1
2
3
4
5
- use rocket::fs::{FileServer, Options};
+ use rocket::fs::{FileServer, rewrite::Prefix};

- FileServer::new("static", Options::DotFiles)
+ FileServer::identity().rewrite(Prefix::checked("static"))

FileServer::without_index() serves files exactly like FileServer::new() without serving index files. Custom rewrites can be written as closures or by implementing Rewriter.

Logging

Rocket v0.6 replaces the log crate with tracing for structured logging. Applications that configure or inspect logging must:

The log_level parameter now accepts tracing level names or a number from 0 to 5. The v0.5 names critical and normal result in a configuration error at launch:

v0.5 log_levelv0.6 log_level
offoff or 0
criticalwarn or 2
normalinfo or 3
debugtrace or 5

The error (1) and debug (4) levels are new. The default level in release mode is now error, which hides warnings. Set log_level to warn to see warnings in release mode as before.

The cli_colors parameter continues to accept true and false and additionally accepts "always", "auto", and "never". The new log_format parameter selects between "pretty" output, the default in debug mode, and "compact" output, the default in release mode.

Logging Macros

With #[macro_use] extern crate rocket, the error!, warn!, info!, debug!, and trace! macros now emit tracing events, so existing uses continue to compile. The macros accept tracing's structured fields:

1
2
3
4
5
#[get("/hello/<name>")]
fn hello(name: &str) -> String {
    info!(name, "saying hello");
    format!("Hello, {name}!")
}

The tracing crate itself is reexported as rocket::tracing. The indented variants of the logging macros, like info_!, and the rocket::log module have been removed. To emit log records instead, depend on log directly: with the trace feature enabled, Rocket's subscriber forwards log records.

Custom Subscribers

Rocket installs its subscriber when an instance of Rocket is first created, for instance, via rocket::build(), unless a global subscriber has already been installed. To use your own subscriber, install it before creating an instance of Rocket. Rocket's subscriber can also be used as a layer in your own subscriber via the trace::subscriber module.

Configuration

Rocket v0.6 moves the configuration of network interfaces out of Config and into connection listeners. The address, port, and tls parameters are still read from the configuration provider, now by the listener. All users must:

A configuration that previously set the port via Config becomes:

1
2
3
4
5
6
7
8
9
10
11
12
13
  use rocket::config::Config;

  #[launch]
  fn rocket() -> _ {
-     let config = Config {
-         port: 1111,
-         ..Config::debug_default()
-     };
+     let figment = Config::figment().merge(("port", 1111));

-     rocket::custom(config)
+     rocket::custom(figment)
  }

To read the address that Rocket is serving on, use Rocket::endpoints() once the instance is in orbit, for instance, in a liftoff fairing:

1
2
3
4
5
6
7
8
9
10
use rocket::fairing::AdHoc;

#[launch]
fn rocket() -> _ {
    rocket::build().attach(AdHoc::on_liftoff("Endpoints", |rocket| Box::pin(async move {
        for endpoint in rocket.endpoints() {
            info!(%endpoint, "listening");
        }
    })))
}

Addresses

The address parameter is now an Endpoint. In addition to an IP address, it accepts a socket address, which includes a port, and a Unix domain socket path prefixed with unix:. A port, if set, replaces the port in a TCP address. For example, to serve on a Unix domain socket:

1
2
[default]
address = "unix:/run/app/rocket.sock"

TLS

TLS configuration in Rocket.toml is unchanged. TLS types are now in the tls module, mutual TLS types in the mtls module, and TlsConfig remains available as rocket::config::TlsConfig. Beyond the renames above:

Errors and Launch

A rocket::Error no longer panics when dropped without being inspected. The #[launch] attribute now generates a main function that reports launch errors with Error::report() and returns an ExitCode. As a result, a failed launch logs the error and exits with a failure status. Previously, it panicked.

Applications that launch Rocket manually should do the same:

1
2
3
4
5
6
7
use std::process::ExitCode;
use rocket::Error;

#[rocket::main]
async fn main() -> ExitCode {
    Error::report(rocket::build().launch().await)
}

Error::pretty_print() has been removed. To log an error, use Trace::trace_error(). Additionally, the variants of ErrorKind have changed:

HTTP and Connections

The rocket::http::hyper module, which reexported hyper and http types, has been removed. Applications that used it, for example, for header name constants, must depend on hyper or http directly or use Rocket's own types.

Several APIs that dealt with connections now work with an Endpoint in place of a SocketAddr, so that they work with any listener:

1
2
- let ip = request.remote().map(|addr| addr.ip());
+ let ip = request.remote().and_then(|endpoint| endpoint.ip());

Custom connection upgrades must update their IoHandler implementations: IoHandler::io() now takes self: Box<Self>, and Response::upgrade() returns an Option<&mut dyn IoHandler>.

1
2
3
4
5
6
7
  #[rocket::async_trait]
  impl IoHandler for MyHandler {
-     async fn io(self: Pin<Box<Self>>, io: IoStream) -> io::Result<()> {
+     async fn io(self: Box<Self>, io: IoStream) -> io::Result<()> {
          /* .. */
      }
  }

Other API Changes

The following changes are less likely to affect applications:

Typed URIs

URIs generated by uri! are now percent-encoded and normalized in the same way as route URIs:

Behavior Changes

The following changes affect the behavior of applications without requiring any code changes:

Contrib

The contrib libraries are largely unchanged. Note the following:

rocket_db_pools also adds support for Diesel's SQLite backend via the new diesel_sqlite feature and diesel::SqlitePool.

Notable New Features

Rocket v0.6 brings many new features that enable new functionality and give applications more control over how they are served. We encourage all users to take advantage of these new features.

Connection Listeners

Rocket v0.6 introduces pluggable connection listeners. A listener accepts connections from any source; Rocket handles the HTTP. Rocket provides listeners for TCP, Unix domain sockets, and TLS over either, and selects among them according to configuration, as described in addresses.

A custom listener implements Listener and, to be configurable, Bind. Rocket can launch on a listener that implements Bind with Rocket::launch_with() or on an existing listener with Rocket::launch_on().

HTTP/3

Rocket v0.6 includes experimental, preview support for HTTP/3 over QUIC. To enable it, enable the http3-preview feature and configure TLS:

1
2
[dependencies]
rocket = { version = "=0.6.0-rc.1", features = ["http3-preview"] }

When TLS is configured, Rocket serves HTTP/3 alongside HTTP/1 and HTTP/2 on the same port and advertises it via the Alt-Svc header. HTTP/3 requires the TLS_AES_128_GCM_SHA256 cipher suite to be enabled.

Tracing

Rocket's logging is now based on tracing. Rocket emits structured events and spans, including a span for each request, and its default subscriber formats them in pretty or compact form. Applications can emit events with the reexported tracing macros and use any tracing subscriber. The trace module contains Rocket's tracing facilities.

XML

The new xml feature adds XML support in the same style as JSON and MessagePack: Xml<T> is a data guard, a form guard, and a responder, and the local client provides LocalRequest::xml() and LocalResponse::into_xml().

Lint Suppression

Rocket's code generation emits warnings for questionable code, such as an unknown media type in a format or a GET route that accepts a body. The new suppress attribute silences these warnings:

1
2
3
#[suppress(dubious_payload)]
#[get("/", data = "<body>")]
fn index(body: &str) { /* .. */ }

Enum Parameters

FromParam can now be derived for enums whose variants have no fields. The derived implementation matches each variant by its name:

1
2
3
4
5
6
7
8
#[derive(FromParam)]
enum Theme {
    Light,
    Dark,
}

#[get("/theme/<theme>")]
fn theme(theme: Theme) { /* .. */ }

And More

Rocket v0.6 includes several other additions:

Getting Help

If you run into any issues upgrading, we encourage you to ask questions via GitHub discussions or via chat at #rocket:mozilla.org on Matrix. The FAQ also provides answers to commonly asked questions.