# Middleware
```rust
use joist::{Middleware, Request, Response, Status};
struct RequireToken;
impl Middleware for RequireToken {
fn before(&self, req: &mut Request) -> Option<Response> {
match req.headers.get("Authorization") {
Some(_) => None,
None => Some(Response::error(Status::UNAUTHORIZED, "missing token")),
}
}
fn after(&self, _req: &Request, res: Response) -> Response {
res.header("X-Checked", "yes")
}
}
```
Both methods have defaults, so implement only the one you need. An empty `impl
Middleware for T {}` is a valid passthrough.
## Ordering
```rust
Server::new(router)
.with(RequestLog) // registered first
.with(RequireToken) // registered second
```
For a request that reaches the handler:
```
RequestLog::before
RequireToken::before
handler
RequireToken::after
RequestLog::after
```
`before` runs in registration order, `after` in reverse. Registering a logger
first therefore means it sees the request first and the response last, which is
the position you want for logging.
## Short-circuiting
Returning `Some(response)` from `before` skips every remaining `before` hook and
the handler. The `after` hooks still run, all of them, in reverse order.
For the same pair with a request that has no token:
```
RequestLog::before
RequireToken::before -> Some(401)
RequireToken::after
RequestLog::after
```
`after` running unconditionally is deliberate. A logger that only saw successful
requests would hide exactly the traffic you most want to see, and a CORS
middleware that skipped rejected responses would turn an authentication failure
into an opaque browser error.
## Why hooks and not `next()`
Most frameworks use an onion: each middleware receives the next one and decides
when to call it.
```rust
// Not how Joist works.
fn handle(&self, req: Request, next: Next) -> Response {
let started = Instant::now();
let res = next.run(req);
println!("{:?}", started.elapsed());
res
}
```
That is strictly more powerful. It lets one middleware hold state across the
handler, which is how request timing is normally done, and Joist's hooks cannot
express it: `after` has no way to see when `before` ran.
The trade was made for three reasons. The ordering is obvious from the trait
rather than from what each implementation chooses to do with `next`. There is no
chain of boxed closures rebuilt per request. And writing one does not require
understanding lifetimes, which for a framework aimed at being readable matters
more than the missing generality.
`RequestLog` deliberately does not report a duration for this reason. It would
have to be invented.
If you need to wrap the handler, wrap the handler:
```rust
fn timed<F>(handler: F) -> impl Fn(&Request) -> Response
where
F: Fn(&Request) -> Response,
{
move |req| {
let started = std::time::Instant::now();
let res = handler(req);
eprintln!("{} took {:?}", req.path, started.elapsed());
res
}
}
## Included
**`RequestLog`** writes one line per request to stderr: peer IP, method, target,
status.
**`Cors`** answers `OPTIONS` preflights from `before` and adds the CORS headers
from `after`, so they land on short-circuited responses too.
```rust
use joist::Cors;
Server::new(router).with(
Cors::new("https://example.com")
.methods("GET, POST")
.headers("Content-Type")
.max_age(600),
)
```
Passing `*` as the origin allows any, which browsers refuse to combine with
credentialed requests.
## Threading
A middleware is shared across every worker thread, so the trait requires `Send +
Sync`. It takes `&self`, not `&mut self`. For mutable state, use an `Arc<Mutex<T>>`
or an atomic:
```rust
struct Counter(std::sync::atomic::AtomicU64);
impl Middleware for Counter {
fn after(&self, _req: &Request, res: Response) -> Response {
self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
res
}
}
```