How to properly register middleware

I am at my wit’s end. I have been trying for days to create an app and register a custom middleware to modify the beforeOutput data of the Dashboard app. For the life of me, I cannot make it work.

I created a skeleton app on GitHub:

I am looking for help to know what to put at ./lib/AppInfo/Application.php:16 to properly load the middleware so I can modify the $output at ./lib/Middleware/TestMiddleware.php:13.

Can anyone help?

Use \OC\AppFramework\Middleware\MiddlewareDispatcher::registerMiddleware

Where can I find the source code of your app?

I figured it out, and I updated my sample app on GitHub with some sample code to hopefully help others who are having trouble.

Basically, I didn’t fully understand how middleware worked. Based on the official documentation, it seemed like registering middleware would allow it to interact with all apps (i.e. at the “server level,” if you will). Instead, middleware must be registered to the container of the app you want to interact with, and in cases where an app doesn’t have a container, you must first register a container for the app and then register your middleware for that container.

Perhaps that isn’t a completely accurate description of how things work, but that’s what I understand at this point, and I was able to get my code to work. If there’s something I’m still missing or comments that might help others, feel free to weigh in.

Thanks!

Hello @ChristophWurst :slight_smile:

I looked the Groupfolders’ Application.php file app : groupfolders/Application.php at stable21 · nextcloud/groupfolders · GitHub .

And the dev team register the Middleware in the register function which is a function from the IBootstrap interface.

So, to register a Middleware for Nextcloud 20 to Nextcloud Latest. Which Middleware we have to use ?

One more, if I register my Middleware in the constructor and use this interface : nextcloud_composer/IContainer.php at stable21 · ChristophWurst/nextcloud_composer · GitHub .

It noted this interface is deprecated from Nextcloud 20 and, at the same time, in the documentation we have to use this interface : https://docs.nextcloud.com/server/latest/developer_manual/basics/middlewares.html .

So, there is an error in the documentation ? :thinking:

You’re looking at the docs of the latest version. That is 22 right now. Here are the ones for 20: https://docs.nextcloud.com/server/20/developer_manual/basics/middlewares.html

Exactly. With 20+ you are supposed to use \OCP\AppFramework\Bootstrap\IRegistrationContext::registerMiddleware