$middleware
import { $middleware } from "dreamkit";
Middlewares are classes that can be exported in the entry and allow you to intervene in requests.
Definition
const $middleware: { self(value: object): typeof $middleware; create(): { new (): { onRequest(): Response | undefined; }; };};
self
Consumes dependencies registered in the IoC context so that they can be used internally by the function.
By default there are a number of registered objects available:
- Request
- Headers
- RequestUrl
- RequestContext
- ResponseHeaders
- AppContext
- Settings created with
$settings
- Sessions created with
$session
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.
create
Create an abstract middleware class with the configured instance. You must override the method onRequest
to implement the middleware logic.
export class MyMiddleware extends $middleware.self({ Headers }).create() { override onRequest() { console.log(this.headers.get("Content-Type")); }}
Examples
Basic usage
import { $route, $middleware, RequestUrl, Link } from "dreamkit";
export class AppMiddleware extends $middleware.self({ RequestUrl }).create() { 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> <br /> <a href="/ping" target="_blank"> Go to ping </a> </> );});