Skip to Content
Drash v3 is in beta. APIs may change.
DocsMiddlewareOverview

Middleware

Middleware extends Resource. It is a decorator , not a separate concept — which is why it has the same HTTP method surface and why it can stand in for the resource it wraps.

In v2.x  these were called “services”. From v3 onward they are “middleware”, matching MDN’s definition .

Ordering

.middleware(A, B, C) nests outermost-first — each middleware wraps the next, and the innermost one wraps your resource:

A request travels inward — A, then B, then C — before it reaches your resource. The response travels back out the same way, so anything a middleware does after its this.next() call runs in the reverse order: C, then B, then A.

Per-Resource Instances

Middleware instances are constructed fresh per resource. Two resources sharing a middleware class do not share an instance.

Do not introduce shared or singleton middleware state across resources — and do not keep per-request state on this, since one instance serves concurrent requests for its resource.

Applying Middleware

You apply middleware by grouping resources.

const group = ResourceGroup .builder() .middleware(Auth) .resources(Users) .build(); const app = Application.builder().resources(...group).build();

Pre-Built Middleware

Drash ships with the following pre-built middleware modules. Each is documented in the Reference pages with its options, defaults, and exports:

MiddlewareWhat it does
AcceptHeaderRejects requests whose Accept header the resource cannot satisfy
CORSAnswers preflight OPTIONS requests and sets CORS response headers
ETagAdds ETag headers and answers 304 Not Modified on a match
RateLimiterLimits requests per client and sets the X-RateLimit-* headers

Each pre-built middleware module is a class you pass to .middleware(). For example:

import { ResourceGroup } from "npm:@drashland/drash/modules/http.native.js"; import { AcceptHeader } from "npm:@drashland/drash/modules/middleware/AcceptHeader.js"; import { CORS } from "npm:@drashland/drash/modules/middleware/CORS.js"; import { ETag } from "npm:@drashland/drash/modules/middleware/ETag.js"; import { RateLimiter } from "npm:@drashland/drash/modules/middleware/RateLimiter.js"; const group = ResourceGroup .builder() .middleware( AcceptHeader(), CORS(), ETag(), RateLimiter(), ) .resources(/* shortened for brevity */) .build();
Last updated on