Backend Javascript NodeJS Serverless

middy.js – stylish middleware engine for AWS Lambda

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 (expressfastifyhapi, 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:

  1. Write your Lambda handlers as usual, focusing mostly on implementing the bare business logic for them.
  2. Import middy and all the middlewares you want to use
  3. 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.
  4. 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.

Stan

Stan is an experienced full-stack developer and software engineer who is focused on web and game development. He is enthusiastic about new technologies. Stan is highly skilled in many programming languages and frameworks, and he always tries to deliver the best approach.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *