Chi ships an optionalDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/go-chi/chi/llms.txt
Use this file to discover all available pages before exploring further.
github.com/go-chi/chi/v5/middleware package that provides a comprehensive suite of production-ready net/http middleware handlers. Every handler follows the standard func(http.Handler) http.Handler signature, so they compose freely with each other and with any other compatible community packages.
Recommended base stack
A sensible starting point for production services includes request identification, client IP capture, logging, panic recovery, and a request timeout:base_stack.go
middleware.Logger should be registered before middleware.Recoverer. Logger records the request when it starts; Recoverer intercepts panics after. Reversing the order means a panic would unwind past Logger before it writes the final log line.Logging & Observability
Logger
Logger logs the start and end of each request, including the HTTP method, path, response status code, bytes written, elapsed time, and client IP. When standard output is a TTY, output is colour-coded by status range.
signature
logger_usage.go
RequestLogger with a LogFormatter implementation:
custom_logger.go
RequestID
RequestID injects a unique request ID into the context of every request. The ID has the form host.example.com/random-000001. If the incoming request already carries an X-Request-Id header, that value is used instead.
signature
request_id_usage.go
Profiler
Profiler mounts net/http/pprof and expvar endpoints under a sub-router. Mount it at a protected path in non-public environments.
signature
profiler_usage.go
Heartbeat
Heartbeat responds to GET or HEAD requests at the specified path with a 200 OK and a single . body, bypassing all route handlers. Useful for load balancer health checks.
signature
heartbeat_usage.go
Resilience
Recoverer
Recoverer catches any panic in a downstream handler, logs the stack trace, and returns HTTP 500. It re-panics http.ErrAbortHandler so WebSocket connections are still cleanly aborted.
signature
recoverer_usage.go
Timeout
Timeout sets a deadline on the request context. Handlers that respect ctx.Done() will be signalled when the deadline expires; after the handler returns, the middleware writes HTTP 504 Gateway Timeout if the context deadline was exceeded.
signature
timeout_usage.go
timeout_handler.go
Throttle
Throttle caps the number of concurrently in-flight requests across all users. Requests that exceed the limit receive HTTP 429 Too Many Requests. Use ThrottleBacklog to hold excess requests in a queue before rejecting them.
signature
throttle_usage.go
Request Processing
Compress
Compress applies gzip or deflate response encoding for clients that advertise support via the Accept-Encoding header. Pass a compression level from the compress/flate package and an optional list of content types to compress (defaults to a sensible set of text and JSON types).
signature
compress_usage.go
NewCompressor directly:
compressor_brotli.go
AllowContentType
AllowContentType enforces an allowlist of request Content-Type values, responding with HTTP 415 Unsupported Media Type if the type is not permitted. Requests with no body (zero Content-Length) pass through without being checked.
signature
allow_content_type_usage.go
AllowContentEncoding
AllowContentEncoding enforces an allowlist of request Content-Encoding values, responding with HTTP 415 Unsupported Media Type if an encoding is not permitted. Requests with no body (zero Content-Length) pass through without being checked.
signature
allow_content_encoding_usage.go
ContentCharset
ContentCharset responds with HTTP 415 when the Content-Type charset parameter is not in the provided list. An empty string in the list allows requests with no charset specified.
signature
content_charset_usage.go
Path & URL
StripSlashes
StripSlashes removes a trailing / from the request path and re-routes, so /articles/ matches the same handler as /articles.
signature
strip_slashes_usage.go
RedirectSlashes
RedirectSlashes issues a 301 redirect stripping the trailing slash, so clients update their bookmarks or links.
signature
redirect_slashes_usage.go
RedirectSlashes is incompatible with http.FileServer. Use StripSlashes in applications that also serve static files.CleanPath
CleanPath normalises double slashes in the request path (e.g., /users//1 → /users/1).
signature
clean_path_usage.go
URLFormat
URLFormat parses the file-extension suffix from the URL path, stores it in the context under middleware.URLFormatCtxKey, and trims it from the routing path so the route pattern does not need to account for it.
signature
url_format_usage.go
GetHead
GetHead automatically routes undefined HEAD requests to their corresponding GET handler. Only the response headers are sent; the body is discarded.
signature
get_head_usage.go
Security & Headers
BasicAuth
BasicAuth adds HTTP Basic authentication to a route or router. Credentials are compared with crypto/subtle.ConstantTimeCompare to defend against timing attacks.
signature
basic_auth_usage.go
NoCache
NoCache sets response headers that instruct both proxy caches and browsers not to cache the response: Cache-Control: no-cache, no-store, …, Pragma: no-cache, and Expires set to the Unix epoch. It also strips incoming ETag-related request headers.
signature
nocache_usage.go
SetHeader
SetHeader is a convenience middleware that sets a single response header key/value pair on every response.
signature
setheader_usage.go
WithValue
WithValue is a convenience middleware that stores a static key/value pair on the request context, equivalent to calling context.WithValue inside a custom middleware.
signature
with_value_usage.go
Sunset
Sunset adds Sunset and Deprecation headers to every response, signalling to API clients that the endpoint is scheduled for removal. Optionally include Link headers pointing to successor documentation.
signature
sunset_usage.go
Complete middleware reference
| Middleware | Signature style | Category |
|---|---|---|
Logger | func(http.Handler) http.Handler | Logging |
RequestLogger(f) | func(http.Handler) http.Handler | Logging |
RequestID | func(http.Handler) http.Handler | Observability |
Profiler() | http.Handler (mount with r.Mount) | Observability |
Heartbeat(endpoint) | func(http.Handler) http.Handler | Observability |
Recoverer | func(http.Handler) http.Handler | Resilience |
Timeout(d) | func(http.Handler) http.Handler | Resilience |
Throttle(n) | func(http.Handler) http.Handler | Resilience |
ThrottleBacklog(n, bl, d) | func(http.Handler) http.Handler | Resilience |
Compress(level, types...) | func(http.Handler) http.Handler | Request Processing |
AllowContentType(types...) | func(http.Handler) http.Handler | Request Processing |
AllowContentEncoding(enc...) | func(http.Handler) http.Handler | Request Processing |
ContentCharset(cs...) | func(http.Handler) http.Handler | Request Processing |
StripSlashes | func(http.Handler) http.Handler | Path & URL |
RedirectSlashes | func(http.Handler) http.Handler | Path & URL |
CleanPath | func(http.Handler) http.Handler | Path & URL |
URLFormat | func(http.Handler) http.Handler | Path & URL |
GetHead | func(http.Handler) http.Handler | Path & URL |
BasicAuth(realm, creds) | func(http.Handler) http.Handler | Security |
NoCache | func(http.Handler) http.Handler | Security |
SetHeader(key, val) | func(http.Handler) http.Handler | Security |
WithValue(key, val) | func(http.Handler) http.Handler | Context |
Sunset(time, links...) | func(http.Handler) http.Handler | API Lifecycle |
ClientIPFromRemoteAddr | func(http.Handler) http.Handler | Client IP |
ClientIPFromHeader(h) | func(http.Handler) http.Handler | Client IP |
ClientIPFromXFF(cidrs...) | func(http.Handler) http.Handler | Client IP |
ClientIPFromXFFTrustedProxies(n) | func(http.Handler) http.Handler | Client IP |