Implementing Middleware

Learn different approaches for implementing middleware.

We'll cover the following

Applying middleware

When it comes to applying middleware, we have two different approaches available to us. Sometimes we have middleware that we want to apply to very specific fields, or even just one field. A logout mutation, for example, might use middleware to mutate the context and remove the current user. Other times, we want to ensure that a particular middleware is always applied to every field in a certain object or every field that has a particular name and return type. This is critical for something like authorization, where you want to protect against a programmer forgetting to specify that a field should be secured. Absinthe provides the two following approaches to handle these types of scenarios:

  • The macro approach
  • The callback approach

Macro approach

When we have specific fields on which we want to place middleware, we’ll want to reach for the middleware/2 macro. As we hinted at earlier, we’ve already been using this macro indirectly via the resolve/1 macro. To recap how it works:

Get hands-on with 1200+ tech skills courses.