Skip to content

MiddlewareClass

Description

Middleware class builder.

Middlewares are classes that can be exported in the dreamkit entry and allow to intervene in requests.

Import

import { MiddlewareClass } from "dreamkit";

Definition

declare const MiddlewareClass: {
(self: 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>
</>
);
});