Skip to content

Middlewares

Arun Prakash edited this page Sep 21, 2025 · 4 revisions

🧩 Middlewares

Middlewares are classes that can inspect/modify requests and responses outside of the request caller.

Consider a scenario where you need to add an authorization logic to your application. You can easily use middleware for this instead of managing the loading the key or details from persistent storage system while the client is being initialized or anywhere else.

You can simply plug in a custom middleware you have created by extending from IWordpressMiddleware to your client, then you can utilize the onLoad() and onUnload() methods in it to load data from your database or storage solution and save it to storage with unload method, then you can utilize the onRequest(...) and onResponse(...) methods to manipulate the request and response just before it is send to the server with complete control.

IWordpressMiddleware System

The IWordpressMiddleware is an abstract base class that defines a contract for middleware in a Wordpress context. It has four methods that subclasses must implement:

  • onLoad: This method is called when the middleware is loaded. It can be used to perform setup operations.
  • onRequest: This method is called for each incoming request. It takes a WordpressRequest object and returns a Future. It can be used to modify the request before it's sent.
  • onResponse: This method is called for each response. It takes a WordpressRawResponse object and returns a Future. It can be used to modify the response before it's returned to the caller.
  • onUnload: This method is called when the middleware is unloaded. It can be used to perform cleanup operations.

Here's an example of a middleware that logs each request and response:

class LoggingMiddleware extends IWordpressMiddleware { @override String get name => 'LoggingMiddleware'; @override Future<void> onLoad() async { print('$name loaded'); } @override Future<WordpressRequest> onRequest(WordpressRequest request) async { print('Request: ${request.method.name} ${request.url}'); return request; } @override Future<WordpressRawResponse> onResponse(WordpressRawResponse response) async { print('Response: ${response.statusCode} ${response.data}'); return response; } @override Future<void> onUnload() async { print('$name unloaded'); } }

Note: No two middleware in a WordpressClient instance should share the same name.

Registering a middleware

To register a new middleware (LoggingMiddleware in this context), you can use the registerMiddleware(middleware) method on WordpressClient instance.

client.registerMiddleware( LoggingMiddleware(), );

Removing a registered middleware

To unregister a middleware, you can use the removeMiddleware method on WordpressClient instance.

client.removeMiddleware( 'LoggingMiddleware', );

If you don’t want to create a class, use DelegatedMiddleware and pass callbacks in the constructor.

Clone this wiki locally