Easily deploy TypeScript project to AWS Lambda using Github Actions

Nir Hadassi
Aspecto
Published in
2 min readMar 18, 2021

Trying to deploy your TypeScript project to AWS Lambda and struggling to do so? You’ve come to the right place.

TypeScript and Lamda can have fun together

I recently worked on a small TypeScript project which I wanted to deploy as a Lambda to AWS.
My project had multiple files and some npm dependencies.

I found some resources online, but none of them really hit the spot. Some didn’t explain how to include the node_modules, some didn’t explain how to do it with TypeScript and some just handled a single file.

In this post, I’ll describe how to prepare the project for deployment and show a detailed example of doing it using Github Actions.

Project Structure

Let’s assume our project structure looks like this:

├── package.json
├── tsconfig.json
├── node_modules
│ ├── module_1
│ ├── module_2
│ └── etc..
└── src
├── index.ts
└── utils.ts

This is our tsconfig.json :

And index.ts contains as the main handler, and uses utils.ts, something like this:

Lambda example (taking advantage of TS using aws-lambda types lib)

Problem

AWS Lamda can only run js files!
Also, AWS Lambda can’t install node_modules for us.

With the default settings, AWS Lambda supports either:

  • Deploying a single index.js file directly.
  • Upload a zip file containing all the project files, which has the index.js in the zip root. So we need to zip the project correctly, without including the parent directory.
    We also need to make sure the node_modules are part of this zip file.
right zip structure when deploying a project to aws lambda
Expected Zip file structure

Prepare for deployment

1. Build the project

We will use TypeScript’s tsc command to transpile the project into js files.
After building, this will be our project structure:

├── package.json
├── tsconfig.json
├── node_modules
├── dist
│ ├── index.js
│ └── utils.js
└── src
├── index.ts
└── utils.ts

2. Move node_modules to dist folder

As mentioned before, AWS Lambda can’t install the node_modules for us, so we need to assure they are located correctly before creating our zip file.

3. ZIP

The project needs to be zipped in the required structure, without the parent directory. The easiest way I found to do it, is to run the following command from the project root:

$ (cd dist && zip -r ../function.zip .)

The zip is now ready for deployment.

Deploy using Github Actions

The deployment part will be done using appleboy/lambda-action, and can be easily substituted with a corresponding AWS CLI command, which comes preinstalled on Github Actions CI machines.

Here’s a detailed example of a Github action:

That’s it! Your Lambda is now ready for work.

--

--