How to terminate a request from middleware with json response


Hi, this is my middleware code:

class IsRoutePermitted {
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Function} next
   * @memberof IsRoutePermitted
  async handle ({ request, response, permissions, session, view, auth }, next, aliases) {

   // permissions is full array of allowed aliases

    if (permissions.length) {

      // aliases is the passed arguments in middleware
      aliases.forEach((alias) => {
        if (permissions.indexOf(alias) === -1) {
          if (request.ajax()) {
            return response.json({
              notification: [{
                status: 'error',
                message: `You are not allowed to access this resource`,
                type: 'toastr'
          session.flash({ errorMessage: 'You are not allowed to access this resource' })
          return response.route('admin.dashboard')
    await next()

In the above code, if the alias is not allowed, I’m trying to terminate the request by sending a json response but somehow its not working or I would say, its still hitting the route handler.