Skip to content

MiddlewareClass

Description

Middleware class builder.

Middlewares are classes that can be exported in the DreamKit input and allow you to intervene in requests.

The middleware constructor allows you to inject dependencies registered by services or use some of those available in the request context: Request, RequestUrl, Headers, IocContext.

It is recommended that the middleware consumes lighter dependencies to avoid loading it with complexity, for example, if you need to access the headers, use Headers and avoid consuming Request.

Import

import { MiddlewareClass } from "dreamkit";

Definition

declare const MiddlewareClass: {
(iocParams: object): {
new (): {
onRequest(): Response | undefined;
};
};
};

Examples

Basic usage

import { $route, MiddlewareClass, RequestUrl, Link } from "dreamkit";
export class AppMiddleware extends MiddlewareClass({
RequestUrl,
}) {
onRequest() {
if (this.requestUrl.is("/section")) {
console.log("hello from other section");
} else if (this.requestUrl.pathname === "/ping") {
return new Response("pong");
}
}
}
export const homeRoute = $route.path("/").create(() => {
return (
<>
<Link href="/section">Go to section</Link>
</>
);
});
export const sectionRoute = $route.path("/section").create(() => {
return (
<>
<button onClick={() => location.reload()}>
Click here to reload and call to the middleware
</button>
<a href="/ping" target="_blank">
Go to ping
</a>
</>
);
});