- Technicalpig
- Posts
- TechnicalPigđ·: Middy
TechnicalPigđ·: Middy
The Node.js Middleware Engine for AWS Lambda
What is Middy?
Middy is a middleware engine for AWS Lambda functions in Node.js, designed to organise Lambda code, eliminate code duplication, and focus on business logic.
It emphasises simplicity and efficiency, allowing developers to push non-functional code to middleware, thus concentrating on the core business logic.
Should You Use Middy?
Middy is ideal for AWS Lambda developers who prioritise clean and maintainable code.
It offers a streamlined approach to handling non-functional concerns like authentication and validation, making your Lambda functions more organised and efficient.
Best Practices
The âBest Practicesâ section on Middy.jsâs documentation offers common tips for optimizing performance and security in AWS Lambda functions using Middy. Key practices include:
Connection reuse: allows you to reuse the first connection established across lambda invocations.
Internal context: Set promises internally in middlewares so that Middy can streamline the flow of asynchronous processing. This means that each middleware waits for the completion of its task before the next one executes
Small node_modules: Use a bundler. A bundler compiles your code and dependencies into a single or a few files, potentially reducing the size and startup time of your Lambda function.
Profiling: Use profiling hooks in
@middy/core
for monitoring middleware, handler execution, and overall performance.
Example of How to Use Middy
Using Middy involves wrapping your Lambda handler with the Middy function and then applying various middleware components. This setup allows for a clear separation between business logic and non-functional concerns, leading to cleaner, more testable code.
Without Middy
exports.handler = async (event) => {
try {
// Your business logic goes here
const responseMessage = "Hello from Lambda!";
return {
statusCode: 200,
body: JSON.stringify({ message: responseMessage })
};
} catch (error) {
console.error(error);
return {
statusCode: 500,
body: JSON.stringify({ error: "Internal Server Error" })
};
}
};
With Middy
const middy = require('@middy/core');
const httpJsonBodyParser = require('@middy/http-json-body-parser');
const baseHandler = async (event) => {
// Your business logic goes here
const responseMessage = "Hello from Middy!";
return {
statusCode: 200,
body: JSON.stringify({ message: responseMessage })
};
};
exports.handler = middy(baseHandler)
.use(httpJsonBodyParser());
Further Readings
For more information, detailed examples, and documentation, please visit the Middy official website.