Overview

General overview on set up of middleware components for Dapr

Dapr allows custom processing pipelines to be defined by chaining a series of middleware components. Middleware pipelines are defined in Dapr configuration files. As with other building block components, middleware components are extensible and can be found in the components-contrib repo.

Middleware in Dapr is described using a Component file with the following schema:

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: <COMPONENT NAME>
  namespace: <NAMESPACE>
spec:
  type: middleware.http.<MIDDLEWARE TYPE>
  version: v1
  metadata:
  - name: <KEY>
    value: <VALUE>
  - name: <KEY>
    value: <VALUE>
...

The type of middleware is determined by the type field. Component setting values such as rate limits, OAuth credentials and other settings are put in the metadata section. Even though metadata values can contain secrets in plain text, it is recommended that you use a secret store.

Next, a Dapr configuration defines the pipeline of middleware components for your application.

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: appconfig
spec:
  httpPipeline:
    handlers:
    - name: <COMPONENT NAME>
      type: middleware.http.<MIDDLEWARE TYPE>
    - name: <COMPONENT NAME>
      type: middleware.http.<MIDDLEWARE TYPE>

Writing a custom middleware

Dapr uses FastHTTP to implement its HTTP server. Hence, your HTTP middleware needs to be written as a FastHTTP handler. Your middleware needs to implement a middleware interface, which defines a GetHandler method that returns a fasthttp.RequestHandler:

type Middleware interface {
  GetHandler(metadata Metadata) (func(h fasthttp.RequestHandler) fasthttp.RequestHandler, error)
}

Your handler implementation can include any inbound logic, outbound logic, or both:

func GetHandler(metadata Metadata) fasthttp.RequestHandler {
  return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
    return func(ctx *fasthttp.RequestCtx) {
      // inboud logic
      h(ctx)  // call the downstream handler
      // outbound logic
    }
  }
}

Adding new middleware components

Your middleware component can be contributed to the components-contrib repository.

After the components-contrib change has been accepted, submit another pull request against the Dapr runtime repository to register the new middleware type. You’ll need to modify runtime.WithHTTPMiddleware method in cmd/daprd/main.go to register your middleware with Dapr’s runtime.