C++26 web framework

crocket

Handlers are functions. Reflection does the rest.

A C++ web framework in the same spirit as Rocket. It's not a port. You write a function, annotate the route, and reflect_routes mounts it. The same structs become JSON, protobuf, and OpenAPI. h2o serves HTTP/1.1, HTTP/2, and TLS.

This page is served by crocket, commit 9b446f8. Latest release: 0.5.1. Live demo: todo.crocket.dev.

01

Type-safe

A {capture} binds to the parameter with the same name. If the names don't match, the build fails and the error names both. /hello/Ada/400 never calls a uint8_t handler. It's 404 path.invalid.

02

No boilerplate

No macros and no route list. Mount a namespace and every annotated function is a route. Helpers without an annotation stay helpers. Reflection runs in the compiler, so a request pays for a function pointer.

03

Plain functions

A handler is a function you can call in a test, step into, and jump to in an editor. build().mount(...).launch() starts the server. Config::from_env() reads CROCKET_PORT and the rest.

04

Extensible

A fairing is a plain struct with on_request or on_response. A custom guard is a FromRequest specialization. A controller is a class whose methods are routes. There's no plugin table.

One route, and it's a function

/hello/Ada/36 runs hello. /hello/Ada/400 doesn't, because 400 isn't a uint8_t.

examples/hello.cpp source
namespace api {

[[= http::get("/hello/{name}/{age}")]]
auto hello(std::string_view name, std::uint8_t age) -> std::string {
  return std::format("Hello, {} year old named {}!", age, name);
}

[[= http::get("/")]]
auto index() -> std::string { return "Try GET /hello/<name>/<age>\n"; }

}  // namespace api

int main() {
  return build(Config::from_env())
      .attach(Logger{})
      .mount("/", reflect_routes<^^api>())
      .launch();
}

What you actually get

Each snippet is from the crocket tree this site is built with. If Rocket has a feature crocket doesn't, it isn't here.

Routes from reflection

Most C++ frameworks register routes at runtime, with a macro, or with a code generator. crocket uses C++26 static reflection. The annotation is an ordinary C++ value, and reflect_routes<^^api>() reads the functions, their annotations, and their parameter names while compiling.

crocket::build()
  .attach(Logger{})
  .mount("/", reflect_routes<^^api>())
  .launch({.listen = "0.0.0.0:8000"});

Overview

JSON and protobuf

A plain struct is the schema. Json<T> reads the body straight into T, with no document tree and no derive macro. Protobuf field numbers follow declaration order. proto::field pins one when you retire a number. Unknown protobuf fields are skipped.

struct NewUser {
  std::string email;                // required
  std::optional<std::string> name;  // may be absent or null
  int age = 0;                      // may be absent: keeps its default
};

[[= http::post("/users")]]
auto create(Json<NewUser> body) -> Json<NewUser> { return body; }

struct HelloRequest {
  std::string name;                                    // field 1
  std::optional<std::string> title;                    // field 2
  [[= proto::field(4)]] std::vector<std::string> tags;  // field 4 (3 was retired)
};

JSON · gRPC

OpenAPI and /docs

GET /openapi.json is OpenAPI 3.1, built at ignite from the handlers. Path types, query members, headers, Json<T>, and Auth<> show up as parameters, bodies, and security. With .docs, GET /docs loads Swagger UI from cdn.jsdelivr.net. This site doesn't. Its policy only allows this origin.

app.attach(OpenApi{{.title = "Orders", .version = "1.4.0", .docs = "/docs"}});

OpenAPI

JWT and OIDC

Link crocket::auth and manage auth::Jwt. Auth<> checks a bearer token. Defaults are RS256, ES256, and EdDSA. HS256 stays off unless CROCKET_AUTH_SECRET is set. A missing token is 401. A valid token without the role is 403 auth.forbidden. JWKS refresh goes through crocket::client. This page doesn't link either library.

[[= http::get("/admin"), = auth::require("admin")]]
auto admin() -> std::string { return "admin\n"; }

return build(Config::from_env())
    .manage(auth::Jwt::from_env())
    .mount("/", reflect_routes<^^api>())
    .launch();

Authentication

Postgres

crocket::db is the API. crocket::pg is the backend, Postgres on libpqxx, and it's built when libpqxx is found. The table name comes from the type: Hero is heroes. An empty optional from find is a 404. Core crocket doesn't include it, and this page doesn't link it.

struct Hero {
  std::int64_t id;
  std::string name;
  std::string alias;
  std::optional<std::string> mentor;
};

[[= http::get("/heroes/{id}")]]
auto get(Db& db, std::int64_t id) -> std::optional<Hero> {
  return db.find<Hero>(id);  // nullopt: 404
}

Databases

Static files

crocket::files serves a directory, or bytes embedded with #embed. Routes match first, including /healthz, whether you mount files or routes first. .headers sets response headers by glob, and those replace Shield's value for the same name. This page is embedded that way.

static constexpr unsigned char index_html[] = {
#embed "web/index.html"
};

.mount("/", files{
    .assets = {asset("index.html", index_html)},
    .cache = {{"*.html", "no-cache"}},
    .headers = {{"*.html", {{"content-security-policy",
                             "default-src 'self'"}}}}})

Static files

Fairings and Shield

Shield is on unless you opt out. Defaults: nosniff, X-Frame-Options: DENY, Content-Security-Policy: default-src 'none'; frame-ancestors 'none', and Referrer-Policy: no-referrer. A header the response already carries is left alone. Fairings are movable types with on_ignite, on_request, on_response, or on_shutdown. No base class.

app.attach(Shield{}.set("content-security-policy", "default-src 'self'"));

Fairings

Health and metrics

Every app has GET /healthz, 200 {"status":"ok"} while the process is serving, and GET /readyz, 200 when every readiness check passes and 503 not_ready when one doesn't. Metrics is opt-in. It serves Prometheus text at GET /metrics, including crocket_http_requests_total and crocket_build_info.

.attach(Metrics{})

Health · Metrics

gRPC and HTTP/2

Unary gRPC methods are functions. Messages are plain structs, and grpc::proto_file prints the .proto, so there isn't a second schema to drift. HTTP/2 is negotiated with ALPN when TLS is on. h2_prior_knowledge accepts h2c on a plain-text port. HTTP/1.1 stays available. Streaming isn't in crocket yet.

[[= grpc::rpc]]
auto say_hello(HelloRequest req, Auth<> auth) -> Result<HelloReply> {
  if (req.name.empty())
    return std::unexpected(ApiError::bad_request("hello.name", "name is required"));
  return HelloReply{"Hello, " + req.name};
}

crocket::build()
    .mount("helloworld", reflect_routes<^^greeter>(), Mode::Grpc)
    .launch({.port = 50051, .h2_prior_knowledge = true});

gRPC

Dev and release profiles

CROCKET_PROFILE=dev binds 127.0.0.1, prints every route, turns on GET /__routes, and puts error detail in the body. Unset, or release, listens on 0.0.0.0:8000 and keeps that detail out of the response. Any other value throws at startup. The other CROCKET_* variables layer on top.

return build(Config::from_env()) // CROCKET_PROFILE=dev ./my_app
    .attach(Logger{})
    .mount("/", reflect_routes<^^api>())
    .launch();

Dev profile

Small, and only the numbers in the repo

./dev bench times a build with h2load, in process, against Rocket 0.5, and against h2o alone. Those results stay in bench/results/, which git ignores. The notes below are the ones written down in the repo. The headline measurements in the next section come from the published write-ups, and each one names its own machine.

  • Routing. Candidates are found in the same time with 10 routes or 1,000, and the lookup allocates nothing. The tree is built at ignite.
  • Hot path, 0.4.0. The changelog records roughly 1.6 times the h2c throughput of the previous crocket, with every production feature on.
  • Event loops. The default is one per physical core. On a 16-core, 32-thread machine, 16 loops served about 1.6 times the requests of 32. Two loops sharing a core compete for it.
  • Binary. Link with -Wl,--gc-sections and the parts of h2o a program never calls drop out, about 300 KB. h2o is linked statically. OpenSSL stays dynamic.
  • Idle workers. They sleep. Each extra thread costs about 8 MB of virtual stack, not resident memory. A 16-connection pool on 4 cores used to cap the Heroes API at about 11k req/s, against 31k once workers followed the pool.

Sources: the routing section and the benchmarks section of the README, docs/ENGINE.md, the building section, and the 0.4.0 changelog. You need GCC 16.2 or later. Ubuntu 26.04's packaged g++-16 is a pre-release snapshot whose reflection bugs break a translation unit that mounts routes.

By the numbers

35.2k req/s

vs Spring Boot's 8.4k

Heroes CRUD, max throughput.

21 MB

vs Spring Boot's 471 MB

Heroes CRUD, peak memory.

JVM ran untuned.

Three DigitalOcean c-4 droplets, Postgres 16, wrk2, median of 3 runs. See the full benchmark

From the blog

Sean's Ramblings, on Hashnode. Titles are the ones on the posts.

Oct 23, 2026

Efficiency is an error-budget input

Takes that Heroes benchmark and prices efficiency as headroom, latency, or a smaller bill. Most of the dollar figures are projections.

More on the blog

Guide, release, demo

The guide lives on this site. Static files, which this page depends on, are in commit 9b446f8 and aren't in the 0.5.1 tag yet.