veryfront/middleware

Import

TypeScript
import {  authRateLimit,  cors,  logger,  MiddlewarePipeline,  rateLimit,  timeout,} from "veryfront/middleware";

Examples

Single middleware

TypeScript
import { cors } from "veryfront/middleware"; const corsMiddleware = cors({ origin: "https://example.com" });

Pipeline composition

TypeScript
import { cors, logger, MiddlewarePipeline, rateLimit, timeout } from "veryfront/middleware"; const pipeline = new MiddlewarePipeline()  .use(cors({ origin: "https://example.com" }))  .use(rateLimit({ maxRequests: 100, windowMs: 60_000 }))  .use(logger({ format: "combined" }))  .use(timeout({ timeoutMs: 30_000 }));

API

middlewarePipeline.use(middleware)

Add a middleware handler to the pipeline.

Returns: this

middlewarePipeline.useFor(pattern, )

Add a middleware handler that only runs for matching URL patterns.

Returns: this

middlewarePipeline.onTeardown(cb)

Register a cleanup callback that runs once per request after each execute()/handle() response body closes, is canceled, or errors. Bodyless, locked, or already-read responses and handler/middleware exceptions clean up before the call resolves.

Returns: this

middlewarePipeline.compose()

Compose all registered middleware into a single handler function.

Returns: MiddlewareHandler

middlewarePipeline.execute(req, env, executionCtx, adapter)

Execute the pipeline for an incoming request.

Returns: <code>Promise<Response></code>

middlewarePipeline.handle(req, handler)

Run the middleware pipeline with a final request handler. Unlike execute, which returns a 404 when no middleware responds, handle invokes the given handler as the terminal step so middleware can add headers, validate auth, etc. before the handler runs.

Returns: <code>Promise<Response></code>

middlewarePipeline.teardown()

Drain and discard all registered teardown callbacks. Unlike the per-request cleanup run by execute() / handle(), this clears callbacks so they never run again.

Returns: <code>Promise<void></code>

middlewarePipeline.getMiddleware()

List registered middleware with metadata.

Returns: <code>Array<{ name?: string; order?: number }></code>

Type Reference

CorsOptions

Options accepted by cors.

PropertyTypeDescriptionSource
origin?string | string[] | OriginValidatorAllowed origins (string, regex, array, or function)source
methods?string[]Allowed HTTP methodssource
allowedHeaders?string[]Allowed request headerssource
exposedHeaders?string[]Headers exposed to clientsource
credentials?booleanAllow credentialssource
maxAge?numberPreflight cache duration (seconds)source

RateLimitOptions

Options accepted by rate limit.

PropertyTypeDescriptionSource
maxRequests?numberMax requests per windowsource
windowMs?numberTime window (ms)source
store?RateLimitStoreStorage backendsource
maxEntries?numberMaximum active identities retained by the default in-memory store. Defaults to 10,000. At capacity, requests for identities without an active entry receive HTTP 503. Active entries are not evicted because doing so would let identity floods reset quotas. Capacity failures log stage=store-increment, failureKind=capacity-exhausted, and the configured capacity. Incompatible with a caller-provided store.source
keyGenerator?<code>(req: Request) => string</code>Function to derive rate limit key from requestsource
trustProxy?booleanTrust proxy-set forwarding headers (X-Forwarded-For) for keying. Defaults to false so forwarded headers are ignored and cannot be used to evade limits. Enable only when a trusted proxy that appends the real client IP sits in front of this middleware.source

MemoryRateLimitStoreOptions

Options accepted by the in-memory rate limit store.

PropertyTypeDescriptionSource
maxEntries?numberMaximum number of active identities retained by the store. Defaults to 10,000. Size this above the peak number of distinct identities expected during one complete rate-limit window, including burst headroom. At capacity, increments for identities without an active entry fail. Active entries are never evicted because identity flooding could otherwise reset an attacker's quota. When used through rateLimit(), capacity exhaustion logs stage=store-increment, failureKind=capacity-exhausted, and the configured capacity.source

LoggerOptions

Options accepted by logger.

PropertyTypeDescriptionSource
format?LogFormatLog format (combined, common, dev, short)source
skip?<code>(req: Request) => boolean</code>Skip logging for matching requestssource
log?<code>(message: string) => void</code>Custom log output functionsource

TimeoutOptions

Options accepted by timeout.

PropertyTypeDescriptionSource
timeoutMs?numberTimeout in milliseconds (default: 75000)source
message?stringCustom message for timeout responsesource
exclude?string[]Paths to exclude from timeout (e.g., health checks)source

Exports

Functions

NameDescriptionSource
authRateLimitPre-configured rate limiter for authentication endpoints (5 req/15min).source
corsCreate CORS middleware.source
devLoggerCreate development request logging middleware.source
getTimeoutFromEnvGets timeout from environment variable REQUEST_TIMEOUT_MSsource
loggerCreate request logging middleware.source
prodLoggerCreate production request logging middleware.source
rateLimitCreate rate-limit middleware.source
timeoutCreates a middleware that enforces request timeouts.source
timeoutFromEnvCreates a timeout middleware with configuration from environmentsource

Classes

NameDescriptionSource
MemoryRateLimitStoreImplement memory rate limit store.source
MiddlewareContextContext for middleware.source
MiddlewarePipelineImplement middleware pipeline.source
RedisRateLimitStoreRedis rate-limit store backed by the registered Redis runtime provider.source

Types

NameDescriptionSource
AuthRateLimitOptionsOptions accepted by the authentication rate-limit preset.source
ContextContext for context.source
CorsOptionsOptions accepted by cors.source
ExecutionContextContext for execution.source
LogFormatPublic API contract for log format.source
LoggerOptionsOptions accepted by logger.source
MemoryRateLimitStoreOptionsOptions accepted by the in-memory rate limit store.source
MiddlewareFactoryPublic API contract for middleware factory.source
MiddlewareHandlerHandler for middleware.source
MiddlewarePipelineOptionsOptions accepted by middleware pipeline.source
NextPublic API contract for next.source
RateLimitOptionsOptions accepted by rate limit.source
RateLimitStorePublic API contract for rate limit store.source
RedisRateLimitOptionsOptions accepted by the provider-backed Redis rate-limit store.source
TimeoutOptionsOptions accepted by timeout.source