One of the main strengths of serverless and AWS Lambda is that, from a developer perspective, your focus is mostly shifted toward implementing business logic.
Anyway, when you are writing a handler, you still have to deal with some common technical concerns outside business logic, like input parsing and validation, output serialization, error handling, etc.
Very often, all this necessary code ends up polluting the pure business logic code in your handlers, making the code harder to read and to maintain.
In other contexts, like generic web frameworks (express, fastify, hapi, etc.), this problem has been solved using the middleware pattern.
This pattern allows developers to isolate these common technical concerns into “steps” that decorate the main business logic code. Middleware functions are generally written as independent modules and then plugged in into the application in a configuration step, thus not polluting the main business logic code that remains clean, readable and easy to maintain.
As you might have already got from our first example here, using middy is very simple and requires just few steps:
- Write your Lambda handlers as usual, focusing mostly on implementing the bare business logic for them.
- Import
middy
and all the middlewares you want to use - Wrap your handler in the
middy()
factory function. This will return a new enhanced instance of your original handler, to which you will be able to attach the middlewares you need. - Attach all the middlewares you need using the function
.use(somemiddleware())
const middy = require('middy')
const { middleware1, middleware2, middleware3 } = require('middy/middlewares')
const originalHandler = (event, context, callback) => { /* your business logic */ }
const handler = middy(originalHandler)
handler
.use(middleware1())
.use(middleware2())
.use(middleware3())
module.exports = { handler }
You can also attach inline middlewares by using the functions .before
, .after
and .onError
.
For a more detailed use case and examples check the Writing a middleware section and the API section.