@edgetime/middleware
Request ID, access log, CORS, security headers, cross-origin write protection, body limits and rate limiting.
npm install @edgetime/middlewareMiddleware for @edgetime/router: request IDs, access logs, CORS, security headers, cross-origin
write protection and rate limiting. No dependencies outside edgetime.
import { createLogger } from '@edgetime/log';import { accessLog, clientAddress, rateLimit, requestId, secureHeaders,} from '@edgetime/middleware';
router.use( requestId(), accessLog({ logger: createLogger() }), secureHeaders(), rateLimit<App>({ limiter: (c) => c.env.API_LIMIT, key: (c) => clientAddress(c.req, 'x-real-ip'), }),);Order matters: put requestId() first so the access log can include the ID.
requestId(options?)
Section titled “requestId(options?)”Sets the requestId var and echoes it in a response header.
| Option | Default | Purpose |
|---|---|---|
header |
x-request-id |
The header read and written. |
trustInbound |
false |
Reuse a well-formed ID sent by the caller. Turn on only behind a proxy you trust to set it. |
generate |
crypto.randomUUID() |
Produces a new ID. If it throws, or returns something a header cannot carry, a UUID is used. |
accessLog({ logger, fields? })
Section titled “accessLog({ logger, fields? })”Writes one record per request with method, path, status, durationMs and requestId. The
query string is left out. A 5xx is logged at error with the thrown error attached, a 4xx at
warn, and everything else at info. fields(request) adds members to each record. A logger or fields function that fails, or returns a promise that rejects, does not affect the response.
secureHeaders(overrides?)
Section titled “secureHeaders(overrides?)”Adds the headers in SECURE_HEADER_DEFAULTS to every response: X-Content-Type-Options,
X-Frame-Options: DENY, Referrer-Policy, Strict-Transport-Security,
Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy, Permissions-Policy and
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'. Pass a value to add or
replace a header, or false to drop one. A header the handler already set is kept. The default
policy suits an API, whose responses load nothing; an application that serves HTML passes its own
content-security-policy.
cors(options)
Section titled “cors(options)”Answers preflight requests and adds CORS headers for allowed origins.
| Option | Default | Purpose |
|---|---|---|
origin |
required | '*', one origin, a list, or a predicate that returns true; a predicate that throws allows nothing. Origins are written as a browser sends them, with no trailing slash; any other spelling throws. With '*' the header is sent on every response, so a cached copy works for any caller. |
methods |
GET, HEAD, POST, PUT, PATCH, DELETE |
Methods allowed in preflight. |
allowHeaders |
echoes the request | Request headers allowed in preflight. Required with credentials, so a credentialed caller is never granted every header it asks for. |
exposeHeaders |
none | Response headers scripts may read. |
credentials |
false |
Allow cookies and HTTP authentication. Throws when combined with origin: '*' or when allowHeaders is not given. |
maxAge |
600 |
Seconds a browser may cache the preflight. |
sameOrigin({ allow? })
Section titled “sameOrigin({ allow? })”Refuses cross-site requests that change state (any method except GET, HEAD and OPTIONS) with
403, using Sec-Fetch-Site and Origin. allow lists other origins that may send them, each written as a browser sends it (https://app.example.com, no trailing slash). A
request with neither header did not come from a browser and passes, so this complements
authentication and does not replace it.
bodyLimit(maxBytes)
Section titled “bodyLimit(maxBytes)”Caps the request body for everything after it. A declared Content-Length over the limit is
refused with 413 before any handler runs. A body without a declared length is counted as it is
read, and reading fails with the same 413 once it passes the limit, whether through the readers
in @edgetime/http, c.req.json(), c.req.arrayBuffer() or a body passed on to fetch(). A
handler that never reads the body is not affected. It swaps the request with
c.replaceRequest().
rateLimit(options)
Section titled “rateLimit(options)”Answers 429 with Retry-After once the limiter refuses a key.
| Option | Default | Purpose |
|---|---|---|
limiter |
required | Returns the limiter for a request: anything with limit({ key }). |
key |
required | What to count by, such as the caller’s identity or the client address. It returns a non-empty string, or undefined when the key is not known for this request; anything else, including a promise, fails the request. |
onMissingKey |
'reject' |
What to do when key returns undefined: 'reject' answers 503, 'skip' lets the request through unlimited. |
retryAfter |
60 |
Seconds sent in Retry-After when the limiter does not report when its window ends. |
detail |
Rate limit exceeded |
Message sent with the 429. |
headers |
false |
Send a RateLimit header, as in the IETF ratelimit-headers draft, with the requests left and the seconds until the window ends, wherever the limiter reported them. |
policy |
default |
The policy name in that header. |
required |
false |
Answer 503 when limiter returns undefined. A function that returns anything but false counts as required. |
timeout |
1000 |
Milliseconds the limiter has to answer before the call counts as failed; at most 60 000. |
onLimiterError |
'reject' |
What to do when the limiter throws or times out: 'reject' answers 503, 'allow' lets the request through unlimited. |
onError |
none | Called with (error, c) for every limiter failure, whichever way the request goes. If it throws, the outcome is unchanged. |
When limiter returns undefined and required is off, the request is not limited. That lets
local runs work without the binding. Set required: true, or a function of the context, wherever
a missing binding must not leave a route unlimited.
When key returns undefined, such as for a request that arrived without the header carrying
the client’s address, the request is refused with 503 by default. Counting every such request
in one shared bucket would let one caller exhaust it for all the others. Use
onMissingKey: 'skip' for local runs where the header is never set.
clientAddress(request, header) reads the client’s address from the header your platform sets,
and returns undefined when it is absent or empty. Name only a header the platform overwrites on every
request; one the client controls lets callers choose their own key.
A limiter is anything with limit({ key }) resolving to { success, remaining?, resetAt? },
where resetAt is when the window ends in Unix milliseconds. When a refusal carries a resetAt
within a year, Retry-After counts down to it instead of using retryAfter.
Every callback fails closed. A limiter, key or required function that throws refuses the
request with 503, or with the HttpError the callback threw.
A limiter that is reachable but failing is a separate decision, made per route with
onLimiterError. Its limit() might reject, throw or not answer within timeout. The default,
'reject', answers 503. Keep it on limits that guard against abuse or cost: sign-in, one-time
codes, password resets, sign-ups, and anything that sends messages or calls a paid service.
'allow' suits a general limit that protects capacity, where an outage of the limiter should not
become an outage of the API. Either way, pass onError so the failure is logged rather than
silent.
withFallback(primary, fallback, { timeout?, onError? }) keeps a limit in place during an outage.
It asks primary and, when that throws or takes longer than timeout (1000 ms by default), asks
fallback instead. The fallback is usually a memoryRateLimiter with a similar limit, so each
instance enforces a rough limit of its own until the shared limiter recovers. If both fail, the
call fails and the route’s onLimiterError decides.
const apiLimit = withFallback(env.API_LIMIT, memoryRateLimiter({ limit: 300, period: 60 }));router.use( '/v1', rateLimit({ limiter: () => apiLimit, key: (c) => clientAddress(c.req, 'x-client-ip'), onLimiterError: 'allow', onError: (error) => log.warn('rate limiter failed', { error }), }),);Create the wrapped limiter once, not per request. Otherwise the fallback’s counts start over on every call.
enforceRateLimit(limiter, key, { retryAfter?, detail?, headers?, policy?, timeout?, onLimiterError?, onError? }) does the same check
inside a handler, for a key that depends on input the handler has parsed. It throws the 429 and
otherwise resolves to what the limiter reported.
memoryRateLimiter({ limit, period, maxKeys? }) is a fixed-window limiter held in process memory,
for single-process servers and tests. It tracks at most maxKeys keys (10 000 by default); past
that, expired windows are dropped, and while every tracked window is still live, new keys share
one overflow window with the same limit. No live count is ever reset, so a flood of distinct keys
cannot clear another caller’s limit; it can only crowd new callers into the overflow window. Keys longer than 256 characters are cut.
Source: packages/middleware on GitHub.