Vix.cpp v2.6.0 is here Read the blog
Skip to content

API Reference

This page is a lookup reference for vix::middleware.

Read the guide pages first if you are new to the module:

  1. Quick Start
  2. App Integration
  3. Core Concepts

Use this page when you already know what you want and need the namespace, type, helper, option, or state object.

Public include

For Vix.cpp v2.6.2 and newer:

cpp
#include <vix.hpp>
#include <vix/middleware.hpp>
1
2

For Vix.cpp v2.6.0 and v2.6.1, App integration headers may need to be included explicitly:

cpp
#include <vix.hpp>
#include <vix/middleware.hpp>

#include <vix/middleware/app/adapter.hpp>
#include <vix/middleware/app/app_middleware.hpp>
#include <vix/middleware/app/http_cache.hpp>
#include <vix/middleware/app/presets.hpp>
1
2
3
4
5
6
7

Main namespaces

NamespacePurpose
vix::middlewareCore middleware aliases, pipeline, HTTP cache
vix::middleware::appvix::App integration helpers and presets
vix::middleware::basicsRecovery, request id, timing, body limit, logger
vix::middleware::securityCORS, CSRF, headers, IP filter, rate limit
vix::middleware::authAPI key, JWT, RBAC, sessions
vix::middleware::parsersJSON, form, multipart parsers
vix::middleware::performanceCompression, ETag, static response hook
vix::middleware::observabilityTracing, metrics, debug trace
vix::middleware::cookiesCookie helpers
vix::middleware::utilsInternal utilities used by middleware

Core types

Defined by the middleware module:

cpp
namespace vix::middleware
{
  using Request = vix::http::Request;
  using Response = vix::http::ResponseWrapper;

  using NextFn = vix::mw::NextFn;
  using Next = vix::mw::Next;
  using NextOnce = vix::mw::NextOnce;

  using Error = vix::mw::Error;
  using Services = vix::mw::Services;
  using Context = vix::mw::Context;

  using MiddlewareFn = std::function<void(Context &, Next)>;

  using HttpMiddleware =
    std::function<void(Request &, Response &, Next)>;

  using Hooks = vix::mw::Hooks;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Core helpers

cpp
vix::middleware::from_http_middleware(...)
vix::middleware::to_http_middleware(...)
vix::middleware::noop()
vix::middleware::use_if(...)
1
2
3
4

Common usage:

cpp
auto mw = vix::middleware::from_http_middleware(my_http_middleware);
1

Error helpers

Re-exported from vix::mw:

cpp
vix::middleware::ok(...)
vix::middleware::fail(...)
vix::middleware::bad_request(...)
vix::middleware::unauthorized(...)
vix::middleware::forbidden(...)
vix::middleware::not_found(...)
vix::middleware::conflict(...)
vix::middleware::internal(...)
vix::middleware::normalize(...)
vix::middleware::to_json(...)
1
2
3
4
5
6
7
8
9
10

Common pattern:

cpp
vix::middleware::Error err;

err.status = 401;
err.code = "unauthorized";
err.message = "Missing token";

ctx.send_error(vix::middleware::normalize(std::move(err)));
1
2
3
4
5
6
7

App integration helpers

Namespace:

cpp
namespace vix::middleware::app
1

Helpers:

cpp
vix::middleware::app::adapt(...)
vix::middleware::app::adapt_ctx(...)
vix::middleware::app::when(...)
vix::middleware::app::protect_path(...)
vix::middleware::app::protect_prefix_mw(...)
vix::middleware::app::protect(...)
vix::middleware::app::protect_prefix(...)
vix::middleware::app::install(...)
vix::middleware::app::install_exact(...)
vix::middleware::app::chain(...)
1
2
3
4
5
6
7
8
9
10

adapt_ctx

Converts MiddlewareFn to vix::App::Middleware.

cpp
app.use(vix::middleware::app::adapt_ctx(
  vix::middleware::basics::request_id()
));
1
2
3

adapt

Converts HttpMiddleware to vix::App::Middleware.

cpp
app.use(vix::middleware::app::adapt(my_http_middleware));
1

when

Runs middleware only when the predicate matches.

cpp
auto only_post = vix::middleware::app::when(
  [](const vix::Request &req)
  {
    return req.method() == "POST";
  },
  vix::middleware::app::body_limit_write_dev(1024)
);
1
2
3
4
5
6
7

protect

Installs middleware on one exact path.

cpp
vix::middleware::app::protect(
  app,
  "/admin",
  vix::middleware::app::api_key_dev("secret")
);
1
2
3
4
5

protect_prefix

Installs middleware on a route prefix.

cpp
vix::middleware::app::protect_prefix(
  app,
  "/admin",
  vix::middleware::app::api_key_dev("secret")
);
1
2
3
4
5

chain

Combines App middlewares in order.

cpp
auto stack = vix::middleware::app::chain(
  vix::middleware::app::body_limit_write_dev(4096),
  vix::middleware::app::json_strict_dev(4096)
);

app.use("/api/users", std::move(stack));
1
2
3
4
5
6

App presets

The App presets return vix::App::Middleware.

Common presets include:

cpp
vix::middleware::app::recovery_dev(...)
vix::middleware::app::request_id_dev(...)
vix::middleware::app::timing_dev(...)
vix::middleware::app::body_limit_dev(...)
vix::middleware::app::body_limit_write_dev(...)

vix::middleware::app::security_headers_dev(...)
vix::middleware::app::cors_dev(...)
vix::middleware::app::csrf_dev(...)
vix::middleware::app::ip_filter_dev(...)
vix::middleware::app::ip_filter_allow_deny_dev(...)
vix::middleware::app::rate_limit_dev(...)
vix::middleware::app::rate_limit_custom_dev(...)

vix::middleware::app::api_key_dev(...)
vix::middleware::app::jwt_dev(...)
vix::middleware::app::session_dev(...)

vix::middleware::app::json_dev(...)
vix::middleware::app::json_strict_dev(...)
vix::middleware::app::form_dev(...)
vix::middleware::app::multipart_dev(...)
vix::middleware::app::multipart_save_dev(...)

vix::middleware::app::http_cache(...)
vix::middleware::app::http_cache_mw(...)
vix::middleware::app::install_http_cache(...)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Example:

cpp
app.use("/api", vix::middleware::app::security_headers_dev());
app.use("/api", vix::middleware::app::cors_dev());
app.use("/api", vix::middleware::app::rate_limit_dev());
app.use("/api/users", vix::middleware::app::json_strict_dev(4096));
1
2
3
4

Basics

Namespace:

cpp
namespace vix::middleware::basics
1

Recovery

cpp
vix::middleware::basics::recovery(...)
1

Options:

cpp
struct RecoveryOptions
{
  bool include_exception_message;
  bool include_code_location;
  std::string code;
  std::string message;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/api", vix::middleware::app::recovery_dev());
1

Lower-level usage:

cpp
vix::middleware::basics::RecoveryOptions opt;

opt.include_exception_message = false;
opt.code = "internal_server_error";
opt.message = "Internal Server Error";

app.use("/api", vix::middleware::app::adapt_ctx(
  vix::middleware::basics::recovery(opt)
));
1
2
3
4
5
6
7
8
9

Request id

cpp
vix::middleware::basics::request_id(...)
1

State type:

cpp
vix::middleware::basics::RequestId
1

Options:

cpp
struct RequestIdOptions
{
  std::string header_name;
  bool accept_incoming;
  bool generate_if_missing;
  bool always_set_response_header;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/api", vix::middleware::app::request_id_dev());
1

Read state:

cpp
auto *rid = req.try_state<vix::middleware::basics::RequestId>();
1

Timing

cpp
vix::middleware::basics::timing(...)
1

State type:

cpp
vix::middleware::basics::Timing
1

Options:

cpp
struct TimingOptions
{
  bool set_x_response_time;
  bool set_server_timing;
  std::string x_response_time_header;
  std::string server_timing_header;
  std::string server_timing_metric;
  bool store_in_state;
};
1
2
3
4
5
6
7
8
9

App usage:

cpp
app.use("/api", vix::middleware::app::timing_dev());
1

Read state:

cpp
auto *timing = req.try_state<vix::middleware::basics::Timing>();
1

Body limit

cpp
vix::middleware::basics::body_limit(...)
1

Options:

cpp
struct BodyLimitOptions
{
  std::size_t max_bytes;
  bool apply_to_get;
  bool allow_chunked;

  std::function<bool(const vix::middleware::Context &)> should_apply;
};
1
2
3
4
5
6
7
8

App usage:

cpp
app.use("/api", vix::middleware::app::body_limit_write_dev(1024 * 1024));
1

Common errors:

StatusCode
411length_required
413payload_too_large

Logger

cpp
vix::middleware::basics::logger(...)
1

Options:

cpp
enum class LogFormat
{
  Text,
  Json
};

struct LoggerOptions
{
  LogFormat format;
  bool log_request_id;
  bool log_timing;
  bool level_from_status;
  bool include_user_agent;
  bool include_forwarded_for;
  bool require_timing;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Logger service interface:

cpp
struct ILogger
{
  virtual ~ILogger() = default;

  virtual void info(std::string_view msg) = 0;
  virtual void warn(std::string_view msg) = 0;
  virtual void error(std::string_view msg) = 0;
};
1
2
3
4
5
6
7
8

Security

Namespace:

cpp
namespace vix::middleware::security
1

Security headers

cpp
vix::middleware::security::headers(...)
1

Options:

cpp
struct SecurityHeadersOptions
{
  bool x_content_type_options;
  bool x_frame_options;
  bool x_xss_protection;
  bool referrer_policy;
  bool permissions_policy;

  bool hsts;
  int hsts_max_age;
  bool hsts_include_subdomains;
  bool hsts_preload;

  std::string content_security_policy;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

App usage:

cpp
app.use("/api", vix::middleware::app::security_headers_dev());
1

CORS

cpp
vix::middleware::security::cors(...)
1

Options:

cpp
struct CorsOptions
{
  std::vector<std::string> allowed_origins;
  bool allow_any_origin;
  bool allow_credentials;

  std::vector<std::string> allow_methods;
  std::vector<std::string> allow_headers;
  std::vector<std::string> expose_headers;

  int max_age_seconds;
  bool vary_origin;
};
1
2
3
4
5
6
7
8
9
10
11
12
13

App usage:

cpp
app.use("/api", vix::middleware::app::cors_dev({
  "https://example.com"
}));
1
2
3

Common error:

StatusCode
403cors_forbidden

CSRF

cpp
vix::middleware::security::csrf(...)
1

Options:

cpp
struct CsrfOptions
{
  std::string cookie_name;
  std::string header_name;
  bool protect_get;
};
1
2
3
4
5
6

App usage:

cpp
app.use("/api", vix::middleware::app::csrf_dev());
1

Common error:

StatusCode
403csrf_failed

IP filter

cpp
vix::middleware::security::ip_filter(...)
1

Options:

cpp
struct IpFilterOptions
{
  std::vector<std::string> allow;
  std::vector<std::string> deny;
  std::string header_name;
  bool use_remote_addr_fallback;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/api", vix::middleware::app::ip_filter_allow_deny_dev(
  "x-forwarded-for",
  {"10.0.0.1"},
  {"9.9.9.9"},
  true
));
1
2
3
4
5
6

Common errors:

StatusCode
403ip_denied
403ip_not_allowed

Rate limit

cpp
vix::middleware::security::rate_limit(...)
1

Options:

cpp
struct RateLimitOptions
{
  double capacity;
  double refill_per_sec;
  bool add_headers;
  std::string key_header;

  std::function<std::string(const vix::middleware::Request &)> key_fn;
};
1
2
3
4
5
6
7
8
9

App usage:

cpp
app.use("/api", vix::middleware::app::rate_limit_dev());
1

Custom usage:

cpp
app.use("/api", vix::middleware::app::rate_limit_custom_dev(
  5.0,
  0.0,
  "x-forwarded-for"
));
1
2
3
4
5

State:

cpp
vix::middleware::security::RateLimiterState
1

Common error:

StatusCode
429rate_limited

Authentication

Namespace:

cpp
namespace vix::middleware::auth
1

API key

cpp
vix::middleware::auth::api_key(...)
1

State type:

cpp
vix::middleware::auth::ApiKey
1

Options:

cpp
struct ApiKeyOptions
{
  std::string header;
  std::string query_param;
  bool required;

  std::unordered_set<std::string> allowed_keys;

  std::function<std::string(const vix::middleware::Request &)> extract;
  std::function<bool(const std::string &)> validate;
};
1
2
3
4
5
6
7
8
9
10
11

App usage:

cpp
app.use("/secure", vix::middleware::app::api_key_dev("secret"));
1

Read state:

cpp
auto &key = req.state<vix::middleware::auth::ApiKey>();
1

Common errors:

StatusCode
401missing_api_key
403invalid_api_key

JWT

cpp
vix::middleware::auth::jwt(...)
1

State type:

cpp
vix::middleware::auth::JwtClaims
1

App usage:

cpp
app.use("/secure", vix::middleware::app::jwt_dev("dev_secret"));
1

Read state:

cpp
auto &claims = req.state<vix::middleware::auth::JwtClaims>();
1

Common errors include missing, malformed, invalid, or unauthorized Bearer tokens.

Use the JWT guide for exact behavior in your build configuration.

RBAC

cpp
vix::middleware::auth::rbac_context(...)
vix::middleware::auth::require_role(...)
vix::middleware::auth::require_any_role(...)
vix::middleware::auth::require_perm(...)
vix::middleware::auth::require_any_perm(...)
vix::middleware::auth::require_all_perms(...)
1
2
3
4
5
6

State type:

cpp
vix::middleware::auth::Authz
1

Options:

cpp
struct RbacOptions
{
  std::string roles_key;
  std::string perms_key;
  bool require_auth;
  bool use_resolver;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/admin", vix::middleware::app::adapt_ctx(
  vix::middleware::auth::rbac_context()
));

app.use("/admin", vix::middleware::app::adapt_ctx(
  vix::middleware::auth::require_role("admin")
));
1
2
3
4
5
6
7

Read state:

cpp
auto &authz = req.state<vix::middleware::auth::Authz>();

authz.has_role("admin");
authz.has_perm("products:write");
1
2
3
4

Resolver interface:

cpp
struct PermissionResolver
{
  virtual ~PermissionResolver() = default;

  virtual void resolve(
    std::string_view subject,
    std::unordered_set<std::string> &roles_inout,
    std::unordered_set<std::string> &perms_inout) = 0;
};
1
2
3
4
5
6
7
8
9

Common errors:

StatusCode
401missing_auth
401missing_authz
403forbidden

Session

cpp
vix::middleware::auth::session(...)
1

State type:

cpp
vix::middleware::auth::Session
1

Options:

cpp
struct SessionOptions
{
  std::shared_ptr<ISessionStore> store;

  std::string secret;
  std::string cookie_name;
  std::string cookie_path;

  bool secure;
  bool http_only;
  std::string same_site;

  std::chrono::seconds ttl;
  bool auto_create;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Store interface:

cpp
class ISessionStore
{
public:
  virtual ~ISessionStore() = default;

  virtual std::optional<Session> load(const std::string &sid) = 0;
  virtual void save(const Session &s, std::chrono::seconds ttl) = 0;
  virtual void destroy(const std::string &sid) = 0;
};
1
2
3
4
5
6
7
8
9

Built-in store:

cpp
vix::middleware::auth::InMemorySessionStore
1

App usage:

cpp
app.use(vix::middleware::app::adapt_ctx(
  vix::middleware::auth::session({
    .secret = "dev"
  })
));
1
2
3
4
5

Read state:

cpp
auto &session = req.state<vix::middleware::auth::Session>();

session.set("n", "1");
auto value = session.get("n");
session.erase("n");
session.destroy();
1
2
3
4
5
6

Parsers

Namespace:

cpp
namespace vix::middleware::parsers
1

JSON

cpp
vix::middleware::parsers::json(...)
1

State type:

cpp
vix::middleware::parsers::JsonBody
1

Options:

cpp
struct JsonParserOptions
{
  bool require_content_type;
  bool allow_empty;
  std::size_t max_bytes;
  bool store_in_state;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/api/users", vix::middleware::app::json_strict_dev(4096));
1

Read state:

cpp
auto &body = req.state<vix::middleware::parsers::JsonBody>();
1

Common errors:

StatusCode
400empty_body
400invalid_json
413payload_too_large
415unsupported_media_type

Form

cpp
vix::middleware::parsers::form(...)
1

State type:

cpp
vix::middleware::parsers::FormBody
1

Options:

cpp
struct FormParserOptions
{
  bool require_content_type;
  std::size_t max_bytes;
  bool store_in_state;
};
1
2
3
4
5
6

App usage:

cpp
app.use("/form", vix::middleware::app::form_dev(4096));
1

Read state:

cpp
auto &form = req.state<vix::middleware::parsers::FormBody>();
1

Multipart

cpp
vix::middleware::parsers::multipart(...)
vix::middleware::parsers::multipart_save(...)
1
2

State types:

cpp
vix::middleware::parsers::MultipartInfo
vix::middleware::parsers::MultipartForm
1
2

Options for metadata parser:

cpp
struct MultipartOptions
{
  bool require_boundary;
  std::size_t max_bytes;
  bool store_in_state;
};
1
2
3
4
5
6

App usage:

cpp
app.use("/upload", vix::middleware::app::multipart_save_dev("uploads"));
1

Read state:

cpp
auto &form = req.state<vix::middleware::parsers::MultipartForm>();
1

Common errors:

StatusCode
400missing_boundary
413payload_too_large
415unsupported_media_type

HTTP helpers

Namespace:

cpp
namespace vix::middleware::cookies
1

Types and helpers:

cpp
vix::middleware::cookies::Cookie

vix::middleware::cookies::parse(...)
vix::middleware::cookies::get(...)
vix::middleware::cookies::set(...)
vix::middleware::cookies::build_set_cookie_value(...)
1
2
3
4
5
6

Example:

cpp
app.get("/cookie", [](vix::Request &, vix::Response &res)
{
  vix::middleware::cookies::Cookie cookie;

  cookie.name = "hello";
  cookie.value = "vix";
  cookie.max_age = 3600;
  cookie.http_only = true;
  cookie.same_site = "Lax";

  vix::middleware::cookies::set(res, cookie);

  res.text("cookie set");
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14

HTTP cache

Namespace:

cpp
namespace vix::middleware
namespace vix::middleware::app
1
2

Lower-level middleware:

cpp
vix::middleware::http_cache(...)
1

App helpers:

cpp
vix::middleware::app::http_cache(...)
vix::middleware::app::http_cache_mw(...)
vix::middleware::app::install_http_cache(...)
vix::middleware::app::make_default_cache(...)
1
2
3
4

App config:

cpp
struct HttpCacheAppConfig
{
  std::string prefix;
  bool only_get;
  int ttl_ms;

  bool allow_bypass;
  std::string bypass_header;
  std::string bypass_value;

  std::vector<std::string> vary_headers;
  std::shared_ptr<vix::cache::Cache> cache;

  bool add_debug_header;
  std::string debug_header;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Lower-level options:

cpp
struct HttpCacheOptions
{
  std::vector<std::string> vary_headers;
  bool cache_200_only;
  bool require_body;

  bool allow_bypass;
  std::string bypass_header;
  std::string bypass_value;

  std::function<vix::cache::CacheContext(Request &)> context_provider;
};
1
2
3
4
5
6
7
8
9
10
11
12

App usage:

cpp
app.use("/api", vix::middleware::app::http_cache({
  .ttl_ms = 30'000,
  .allow_bypass = true,
  .bypass_header = "x-vix-cache",
  .bypass_value = "bypass",
  .vary_headers = {"accept-language"}
}));
1
2
3
4
5
6
7

Common cache status header:

txt
x-vix-cache-status: miss
x-vix-cache-status: hit
x-vix-cache-status: bypass
1
2
3

Performance

Namespace:

cpp
namespace vix::middleware::performance
1

Compression

cpp
vix::middleware::performance::compression(...)
1

Options:

cpp
struct CompressionOptions
{
  std::size_t min_size;
  bool add_vary;
  bool enabled;
  int gzip_level;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/api", vix::middleware::app::adapt_ctx(
  vix::middleware::performance::compression({
    .min_size = 1024,
    .add_vary = true,
    .enabled = true
  })
));
1
2
3
4
5
6
7

ETag

cpp
vix::middleware::performance::etag(...)
1

Options:

cpp
struct EtagOptions
{
  bool weak;
  bool add_cache_control_if_missing;
  std::string cache_control;
  std::size_t min_body_size;
};
1
2
3
4
5
6
7

App usage:

cpp
app.use("/api", vix::middleware::app::adapt_ctx(
  vix::middleware::performance::etag({
    .weak = true,
    .add_cache_control_if_missing = false,
    .min_body_size = 1
  })
));
1
2
3
4
5
6
7

Static response compression hook

Static files are served by Core through:

cpp
app.static_dir(...);
1

The middleware module can only enhance static responses through a hook:

cpp
vix::App::set_static_response_hook(
  vix::middleware::performance::compressed_static_response_hook()
);
1
2
3

With options:

cpp
vix::middleware::performance::CompressionOptions options{
  .min_size = 1024,
  .add_vary = true,
  .enabled = true
};

vix::App::set_static_response_hook(
  vix::middleware::performance::compressed_static_response_hook(options)
);
1
2
3
4
5
6
7
8
9

Observability

Namespace:

cpp
namespace vix::middleware::observability
1

Tracing

cpp
vix::middleware::observability::tracing_hooks(...)
vix::middleware::observability::tracing_mw(...)
1
2

State type:

cpp
vix::middleware::observability::TraceContext
1

Options:

cpp
struct TracingOptions
{
  std::string trace_header;
  std::string span_header;
  std::string parent_span_header;

  bool accept_incoming_trace;
  bool accept_incoming_span;
  bool emit_response_headers;
  bool include_parent_in_response;

  std::function<void(
    vix::middleware::Context &,
    TraceContext &
  )> enrich;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

App usage:

cpp
app.use("/api", vix::middleware::app::adapt_ctx(
  vix::middleware::observability::tracing_mw()
));
1
2
3

Read state:

cpp
auto *trace =
  req.try_state<vix::middleware::observability::TraceContext>();
1
2

Debug trace

cpp
vix::middleware::observability::debug_trace_hooks(...)
vix::middleware::observability::debug_trace_mw(...)
1
2

Sink interface:

cpp
class IDebugTraceSink
{
public:
  virtual ~IDebugTraceSink() = default;
  virtual void log(std::string_view line) = 0;
};
1
2
3
4
5
6

Built-in sink:

cpp
vix::middleware::observability::InMemoryDebugTrace
1

Options:

cpp
struct DebugTraceOptions
{
  bool include_method;
  bool include_path;
  bool include_status;
  bool include_duration_ms;
  bool include_trace_ids;
  std::string prefix;
};
1
2
3
4
5
6
7
8
9

App usage:

cpp
auto sink =
  std::make_shared<vix::middleware::observability::InMemoryDebugTrace>();

app.use("/api", vix::middleware::app::adapt_ctx(
  vix::middleware::observability::debug_trace_mw(sink)
));
1
2
3
4
5
6

Metrics

cpp
vix::middleware::observability::metrics_hooks(...)
1

Built-in sink:

cpp
vix::middleware::observability::InMemoryMetrics
1

Pipeline usage:

cpp
auto metrics =
  std::make_shared<vix::middleware::observability::InMemoryMetrics>();

vix::middleware::HttpPipeline pipeline;

pipeline.set_hooks(
  vix::middleware::observability::metrics_hooks(metrics)
);
1
2
3
4
5
6
7
8

Safe labels

cpp
vix::middleware::observability::safe_method(req)
vix::middleware::observability::safe_path(req)
1
2

Pipeline

Namespace:

cpp
namespace vix::middleware
1

Type:

cpp
vix::middleware::HttpPipeline
1

Main methods:

cpp
pipeline.use(...)
pipeline.run(...)
pipeline.clear()
pipeline.size()
pipeline.services()
pipeline.hooks()
pipeline.set_hooks(...)
pipeline.enable_dev_observability(...)
1
2
3
4
5
6
7
8

Example:

cpp
vix::middleware::HttpPipeline pipeline;

pipeline.use(vix::middleware::basics::request_id());
pipeline.use(vix::middleware::basics::timing());

pipeline.run(req, res, [](auto &, auto &out)
{
  out.status(200).text("OK");
});
1
2
3
4
5
6
7
8
9

Use HttpPipeline for tests and custom integrations.

Use vix::App for normal applications.

Utilities

Namespace:

cpp
namespace vix::middleware::utils
1

Common utilities:

cpp
vix::middleware::utils::Clock
vix::middleware::utils::TokenBucket
vix::middleware::utils::JsonWriter
vix::middleware::utils::KeyBuilder

vix::middleware::utils::to_lower(...)
vix::middleware::utils::iequals(...)
vix::middleware::utils::trim_copy(...)
vix::middleware::utils::split_csv(...)
vix::middleware::utils::join_csv(...)
vix::middleware::utils::first_token(...)
vix::middleware::utils::normalize_keys_in_place(...)
1
2
3
4
5
6
7
8
9
10
11
12

Most users do not need these directly.

They are mainly used by middleware implementations.

Common state types

MiddlewareState type
request_id()vix::middleware::basics::RequestId
timing()vix::middleware::basics::Timing
api_key()vix::middleware::auth::ApiKey
jwt()vix::middleware::auth::JwtClaims
rbac_context()vix::middleware::auth::Authz
session()vix::middleware::auth::Session
json()vix::middleware::parsers::JsonBody
form()vix::middleware::parsers::FormBody
multipart()vix::middleware::parsers::MultipartInfo
multipart_save()vix::middleware::parsers::MultipartForm
tracing_mw()vix::middleware::observability::TraceContext

Read required state:

cpp
auto &body = req.state<vix::middleware::parsers::JsonBody>();
1

Read optional state:

cpp
auto *trace = req.try_state<vix::middleware::observability::TraceContext>();
1

Common status codes

StatusTypical codeSource
400empty_bodyJSON parser
400invalid_jsonJSON parser
400missing_boundaryMultipart
401missing_api_keyAPI key
401missing_authJWT or RBAC
401missing_authzRBAC
403invalid_api_keyAPI key
403forbiddenRBAC
403csrf_failedCSRF
403cors_forbiddenCORS
403ip_deniedIP filter
403ip_not_allowedIP filter
411length_requiredBody limit
413payload_too_largeBody limit or parser
415unsupported_media_typeParser
429rate_limitedRate limit
500internal_server_errorRecovery

A practical starting stack:

cpp
#include <vix.hpp>
#include <vix/middleware.hpp>

using namespace vix;

int main()
{
  App app;

  app.use("/api", middleware::app::recovery_dev());
  app.use("/api", middleware::app::request_id_dev());
  app.use("/api", middleware::app::timing_dev());

  app.use("/api", middleware::app::security_headers_dev());
  app.use("/api", middleware::app::cors_dev({"https://example.com"}));
  app.use("/api", middleware::app::rate_limit_dev());

  app.use("/api", middleware::app::body_limit_write_dev(1024 * 1024));

  app.use("/api/users", middleware::app::json_strict_dev(4096));
  app.use("/api/admin", middleware::app::api_key_dev("secret"));

  app.get("/api/health", [](Request &, Response &res)
  {
    res.json({
      "ok", true
    });
  });

  app.post("/api/users", [](Request &req, Response &res)
  {
    auto &body = req.state<middleware::parsers::JsonBody>();

    res.status(201).json({
      "ok", true,
      "body", body.value.dump()
    });
  });

  app.get("/api/admin/status", [](Request &, Response &res)
  {
    res.json({
      "ok", true,
      "admin", true
    });
  });

  app.run(8080);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

Static files note

Static file serving is not a middleware feature.

Use Core:

cpp
app.static_dir(...);
1

Use middleware only for optional static response enhancement:

cpp
vix::App::set_static_response_hook(
  vix::middleware::performance::compressed_static_response_hook()
);
1
2
3

Remember:

txt
Core serves static files.
Middleware enhances HTTP behavior.
1
2

Released under the MIT License.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.