Middleware
Creating Middleware
A middleware is a piece of code that is run before or after a request is handled. It might modify the Request
or Response
.
Create a middleware by conforming to the Middleware
protocol. It has a single function intercept
which takes a Request
and next
closure. It returns an EventLoopFuture<Response>
.
Accessing the Request
If you’d like to do something with the Request
before it is handled, you can do so before calling next
. Be sure to call and return next
when you’re finished!
You may also do something with the request asynchronously, just be sure to continue the chain with next(req)
when you are finished.
Setting Data on a Request
Sometimes you may want a Middleware
to add some data to a Request
. For example, you may want to authenticate an incoming request with a Middleware
and then add a User
to it for handlers down the chain to access.
You can set generic data on a Request
using Request.set
and then access it in subsequent Middleware
or handlers via Request.get
.
For example, you might be doing some experiments with a homegrown ExperimentConfig
type. You’d like to assign random configurations of that type on a per-request basis. You might do so with a Middleware
:
You would then intercept requests with that Middleware
and utilize the set ExperimentConfig
in your handlers.
Accessing the Response
If you’d like to do something with the Response
of the handled request, you can plug into the future returned by next
.
Adding Middleware to Your Application
There are a few ways to have a Middleware
intercept requests.
Global Intercepting
If you’d like a middleware to intercept all requests on an Application
, you can add it via Application.useAll
.
Specific Intercepting
A Middleware
can be setup to only intercept requests to specific handlers via the .use(_ middleware: Middleware)
function on an Application
. The Middleware
will intercept all requests to the subsequently defined handlers.
There is also a .group
function that takes a Middleware
. The Middleware
will only intercept requests handled by handlers defined in the closure.