How to get 'ctx.state.user' in custom middleware

The rough break down of how a policy works:

module.exports = async (ctx, next) => {
  // Anything here runs before the controller
  await next();
  // Anything here runs after the controller
};

Simply removing the return part of the return await next() allows you to run them in a beforeX/afterX style. The general use-case for a policy is to restrict access or return errors to the user for advanced validation but they can be used for other purposes (like injecting headers to the response).

A good purpose I’ve seen for this is narrow scoped rate-limiting, where you only really want to rate limit a handful of endpoints.

1 Like