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:
| Middleware | What it does |
|---|---|
| AcceptHeader | Rejects requests whose Accept header the resource cannot satisfy |
| CORS | Answers preflight OPTIONS requests and sets CORS response headers |
| ETag | Adds ETag headers and answers 304 Not Modified on a match |
| RateLimiter | Limits requests per client and sets the X-RateLimit-* headers |
Each pre-built middleware module is a class you pass to .middleware(). For example:
Deno
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();