middy-profiler is an AWS Lambda middleware designed to capture CPU profiling data for Node.js functions, integrating seamlessly with the Middy framework. As of its current stable version 1.0.11, it enables developers to identify performance bottlenecks within their serverless functions by saving detailed CPU profiles to a specified AWS S3 bucket. These `.cpuprofile` files can then be analyzed using standard tools like Chrome DevTools for in-depth performance analysis. The package maintains a consistent release cadence with minor updates addressing features like conditional reporting, start delays, and coldstart profiling. Key differentiators include its tight integration with Middy, a standalone usage option, and the ability to profile module initialization during cold starts, which is crucial for optimizing initial function execution. Proper configuration of an S3 bucket and corresponding Lambda permissions are mandatory for its operation. It requires `@middy/core` version 2.0.0 or higher.
npm install middy-profilerVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to integrate middy-profiler into an AWS Lambda handler using ESM, configure the S3 bucket for profile storage, and apply the middleware to an existing function.
Ensure `MIDDY_PROFILER_S3_BUCKET_NAME` environment variable is set or pass `s3: { bucketName: '...' }` in the profiler middleware options.Update the AWS Lambda function's IAM role to include `s3:PutObject` permission for the target S3 bucket. Example policy: `{"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": "arn:aws:s3:::your-bucket-name/*"}`.Set `NODE_OPTIONS` in your Lambda function's environment variables to include `--require /path/to/middy-profiler/bootstrap.js`. This path is typically derived from the Lambda layer or node_modules path.
Upgrade your `@middy/core` package to version `2.0.0` or later by running `npm install @middy/core@^2`.
Set the `MIDDY_PROFILER_S3_BUCKET_NAME` environment variable in your Lambda configuration or provide the bucket name directly in the middleware options: `profiler({ s3: { bucketName: 'your-bucket' } })`.Verify that the S3 bucket specified in your configuration (environment variable or middleware options) actually exists in the correct AWS region.
Grant the `s3:PutObject` permission to your Lambda function's IAM role for the target S3 bucket. Ensure the resource ARN matches your bucket and key prefix (e.g., `arn:aws:s3:::your-bucket-name/*`).
Ensure `@middy/core` is installed (`npm install @middy/core@^2`) and imported correctly: `import middy from '@middy/core';` for ESM or `const middy = require('@middy/core');` for CommonJS.