DEV Community

Cover image for 🚀 Top-level await in AWS Lamba with TypeScript
Eduardo Rabelo
Eduardo Rabelo

Posted on • Updated on

🚀 Top-level await in AWS Lamba with TypeScript

On version 14.8.0 release, almost two years ago, Node.js closed the issue#34558, called module: unflag Top-Level Await. From version 14.8 we can use await outside an async function inside an ES module.

After almost two years, we can find Node.js code not taking advantage of it. Furthermore, the complexity of configuring it increases when we consider the usage of bundlers and compilers, like esbuild or TypeScript.

Execution performance

In ephemeral environments like AWS Lambda, any millisecond we can shave is a flawless victory. Earlier this year, the AWS Lambda runtime added full support for Node.js 14+ features.

As Dan Fox (Principal Specialist Solutions Architect Serverless) explained in his article, we can see around ~45% performance improvements:

45% performance improvements in scenarios using top-level await in AWS Lambda Node.js runtime

Transpiling TypeScript to ES Modules

With a combination of AWS Lambda Serverless development tools, we can easily take advantage of these improvements.

My example uses:

The secret sauce is to configure esbuild to output Node.js ES modules files with .mjs extension with the following esbuild options:

format: "esm"
outputFileExtension: ".mjs"
platform: "node"
target: "esnext"
Enter fullscreen mode Exit fullscreen mode

With that in place, you can have a fully typed AWS Lambda code in TypeScript and take advantage of executing await outside the handler function, improving the response time for the service consumers.

You can check the entire demo on my GitHub:

GitHub logo oieduardorabelo / top-level-await-in-aws-lamba-with-typescript

🚀 Using top-level await in AWS Lambda with TypeScript, esbuild and Serverless Framework

🚀 Top-level await in AWS Lamba with TypeScript

Articles

Summary

This repository demonstrates Node.js ES modules and top-level await in AWS Lambda while developing your code in TypeScript.

How does that work?

We use serverless-esbuild to transpile our TypeScript code to JavaScript.

The secret sauce is to configure esbuild to output Node.js ES modules files with .mjs extension with the following esbuild options:

format: "esm"
outputFileExtension: ".mjs"
platform: "node"
target: "esnext"
Enter fullscreen mode Exit fullscreen mode

With that in place, you can have a fully typed AWS Lambda code in TypeScript and take advantage of executing await outside the handler function, improving the response time for the service consumers.

As Dan Fox (Principal Specialist Solutions Architect Serverless) explained in his article, we can see around ~45% performance improvements:

https://aws.amazon.com/blogs/compute/using-node-js-es-modules-and-top-level-await-in-aws-lambda/

Top comments (0)