Middleware
The middleware Hono ships, one lesson each, on the cats API from Basics: logging and request ids, CORS, body limits, ETags, secure headers and CSRF, then basic auth, bearer tokens, JWTs, and how to combine guards. Every lesson reads the docs' page for that middleware and grades what it does on the wire.
- lessons
- 9
- level
- intermediate
- time
- 3 hours
Seeing requests
What every request should leave behind: a log line, an id, and a body a human can read.
- 1Logging and request ids
Give every request a log line, an id that follows it from the client through the handler to the response, and a JSON body a human can read when asked.
Read the theory
Protecting the edge
What a browser needs to be allowed to call the API, what the API refuses to accept, and what it tells caches and browsers about itself.
- 2CORS
Let a browser app on another origin call the cats API: answer the preflight, name the origins, methods and headers that are allowed, expose a custom header, and keep the rest of the API untouched.
Read the theory - 3Body limits
Refuse a request body before a handler reads it: a JSON limit with a message of your own, and a raw upload limit with the middleware’s default 413.
Read the theory - 4ETags
Tag every cat response with etag() so a client that already has it gets 304 and no body, watch the tag change when the cat changes, and pair it with Cache-Control.
Read the theory - 5Secure headers and CSRF
Tell browsers how to treat the API's responses with secureHeaders(), tune two of its headers and add a content security policy, then stop cross-site forms from posting with csrf().
Read the theory
Who is asking
Three ways to identify a caller, from a shared password to a signed token, and how to combine them.
- 6Basic auth
Put a username and password in front of the admin routes with basicAuth(), on a path prefix and on a single route, and let the handler know who signed in.
Read the theory - 7Bearer tokens
Protect the API with tokens in the Authorization header: one token that may read, one that may also write, and the three different refusals a client can get.
Read the theory - 8JSON Web Tokens
Issue a signed token at login with sign() and guard the API with jwt(): the token carries who the caller is and what they may do, and the server trusts it without a lookup.
Read the theory - 9Combining middleware
Build one guard out of several with the combinators in hono/combine: accept either of two credentials with some(), require several checks with every(), and carve out public routes with except().
Read the theory