Passing data from middleware to controller

Hi everyone, i’m trying to pass authentication data from a middleware to a controller (the goal is to render them in the related view when the user is logged in).

This is the middleware, where i tried to save theuserData object in ctx.

class UserData {
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Function} next
  async handle ({ auth }, next, ctx ) {
    if ( {
        console.log("user found")
        let userId =`${}_${auth.user.surname}_${}`,
        fullName = `${} ${auth.user.surname}`
        ctx.userData = await {"username" :, "id" : userId, "full" : fullName}
          await next()
    } else {
          console.log("user NOT found")
          ctx.userData = {}
          await next()

then, this is the controller method:

async home({ view, userData }) {
        return view.render("homepage", userData)

And this is the output of the logs:

user found
{ username: 'Jonh', id: 'John_Smith_21', full: 'John Smith' }

userData object should been stored in http context ctx, however in the controller there is no sign of that. What did i do wrong?

1 Like

Hi @Chereda94,
With your middleware you can edit the request object from ctx (ctx.request) to send data from middlewares to controllers.

Try something like :

async handle ({ auth, request }, next, properties) {
  request.userData = await ... 
  await next()

And now use request.userData on your controller.

Example on documentation (request object): creating_middleware

The third argument of the handle function is not ctx but properties. You can see more informations here : middleware_properties