I managed to successfully create middleware for api/users/:id route, which is related to users-permissions plugin.
First, write your middleware logic in src/middlewares/your-custom-middleware.js:
module.exports = (config, { strapi }) => {
return async (ctx, next) => {
//...here
}
}
This middleware will be global, but do not add it into config/middlewares.js array, if you need to check for things like authorization first, otherwise any unauthed request to every route will be blocked.
Then, you have to inject this middleware into users-permissions plugin in src/index.js, like shown here ← this is example that was referenced in the comment section under official Strapi tutorial on YT.
So, in there, paste “global::your-custom-middleware” and route handlers/method requests. The example is something like this:
'use strict';
module.exports = {
register({ strapi }) {
const userRoutes = strapi.plugins["users-permissions"].routes["content-api"].routes;
const yourCustomMiddleware = "global::your-custom-middleware";
// get users-permissions routes you want to attach middleware to
const findUpdateUser = userRoutes.findIndex(
(route) => route.handler === "user.update" && route.method === "PUT"
);
const findDeleteUser = userRoutes.findIndex(
(route) => route.handler === "user.destroy" && route.method === "DELETE"
);
function initializeRoute(routes, index) {
routes[index].config.middlewares = routes[index].config.middlewares || [];
routes[index].config.policies = routes[index].config.policies || [];
}
// attach middleware to routes if they are present
if (findUpdateUser) {
initializeRoute(userRoutes, findUpdateUser);
userRoutes[findUpdateUser].config.middlewares.push(yourCustomMiddleware);
}
if (findDeleteUser) {
initializeRoute(userRoutes, findDeleteUser);
userRoutes[findDeleteUser].config.middlewares.push(yourCustomMiddleware);
}
console.log(userRoutes[findUpdateUser], "userRoutes[findUpdateUser]")
console.log(userRoutes[findDeleteUser], "userRoutes[findDeleteUser]")
},
bootstrap(/*{ strapi }*/) {},
};
Don’t forget to allow access to users-permissions routes in Strapi admin: Settings → Users & Permissions Plugin → Roles → Authenticated/Public → Users-permissions → User section. In there you will also find the names of the route handlers, if you click on gear icon that appears while hovering over them; they will be shown to the right of the section