Unable to modify Request Body in Middleware for Entity Creation strapi v4

I’ve set up a middleware for the /api/deposits route to check if the user is authenticated. If authenticated, I want to modify the users_permissions_user field in the request body before the entity creation process.

I have tried the following:

Here’s a simplified version of my middleware:

  1. ctx.request.body.users_permissions_user = 7;
  2. ctx.request.body = { …ctx.request.body, users_permissions_user: 7 }
  3. ctx.set(‘users_permissions_user’, 7)
module.exports = async (ctx, next) => {
  // Check if user is authenticated
  if (ctx.state.user) {
    // Attempting to modify the request body to set users_permissions_user
    // Attempt 1
    // ctx.request.body.users_permissions_user = 7;

    // Attempt 2
    // ctx.request = { ...ctx.request.body, users_permissions_user: 7 };

    // Attempt 3
    // ctx.set('users_permissions_user', 7);
  }

  // Continue with the next middleware or the entity creation process
  await next();
};

However, none of my attempts to modify the users_permissions_user field in the request body seem to work. The field remains unset after the request is processed.

Is there a recommended way to modify the request body in a middleware for entity creation? Any help or insights would be greatly appreciated.

Thanks!

1 Like

Any Updates on the subject?
I am trying myself to simply append the user in the request via a middleware
I have also attempted the approaches and simply the updated ctx is not being forwarded in the controller.

My Temp solution is applying the logic in the controller, but its something i want to re-use all over my project.