rust
38 lines · 7 steps
Request ID middleware in Axum
An Axum middleware that reuses or mints an X-Request-ID and threads it through the request and response.
Explained by
highlit
1use axum::{
2 body::Body,
3 extract::Request,
4 http::{header::HeaderValue, HeaderName},
5 middleware::Next,
6 response::Response,
7};
8use uuid::Uuid;
9
10static REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
11
12#[derive(Clone, Debug)]
13pub struct RequestId(pub String);
14
15pub async fn propagate_request_id(mut request: Request<Body>, next: Next) -> Response {
16 let request_id = request
17 .headers()
18 .get(&REQUEST_ID)
19 .and_then(|value| value.to_str().ok())
20 .map(str::to_owned)
21 .unwrap_or_else(|| Uuid::new_v4().to_string());
22
23 request
24 .extensions_mut()
25 .insert(RequestId(request_id.clone()));
26
27 if let Ok(header_value) = HeaderValue::from_str(&request_id) {
28 request.headers_mut().insert(REQUEST_ID.clone(), header_value.clone());
29
30 let mut response = next.run(request).await;
31 response
32 .headers_mut()
33 .insert(REQUEST_ID.clone(), header_value);
34 return response;
35 }
36
37 next.run(request).await
38}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reusing an inbound request ID when present preserves trace continuity across services.
- 2Request extensions let middleware hand typed data to downstream handlers without touching headers.
- 3Echoing the ID onto the response lets clients correlate their call with your logs.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/request-id-middleware-in-axum-explained-rust-df34/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.