It's Day 1 of Launch Week and we're kicking off with a highly requested feature...
You asked, we delivered! Starting today, you can define your own middleware in Encore.ts.
While common use cases like authentication, logging, and tracing are already built-in, Custom Middleware now lets you create middleware tailored to your application with ease. This is great for cases where you want to write reusable functionality that applies to multiple API endpoints.
Encore.ts makes it simple to create middleware by letting you attach middleware functions to specific services through the service definitions configuration.
Middleware can be configured with a target
option to specify which API endpoints it applies to, such as those requiring authentication.
The simplest way to create a middleware is to use the middleware
helper in encore.dev/api
,
here is an example of a middleware that will run for endpoints that require auth:
import { middleware } from "encore.dev/api";
export default new Service("myService", {
middlewares: [
middleware({ target: { auth: true } }, async (req, next) => {
// do something before the api handler
const resp = await next(req);
// do something after the api handler
return resp
})
]
});
Middleware runs in the order they are defined in the service definitions configuration, i.e:
export default new Service("myService", {
middlewares: [
first,
second,
third
],
});
Middleware forms a chain, allowing each middleware to introspect and process
the incoming request before handing it off to the next middleware by calling the
next
function that's passed in as an argument. For the last middleware in the
chain, calling next
results in the actual API handler being called.
The req
parameter provides information about the incoming request, it has different fields
depending on what kind of handler it is.
This design enables you to add custom logic both before and after an API handler is executed, making it easy to inspect the request, modify the response, or enforce rules by throwing errors.
The target option specifies which endpoints within the service the middleware should run on. If not set, the middleware will run for all endpoints by default.
For better performance, use the target
option instead of filtering within the middleware function.
This enables calculating applicable middleware per endpoint during startup, reducing runtime overhead.
If you're already using Encore, update using encore version update
.
If you're new to Encore, install using the instructions below and then create an example app using encore app create
.
$ brew install encoredev/tap/encore
If you have questions or just want to hang out with other Encore developers, join our community on Discord.