How to Build a serverless backend AWS Lambda function to upload a file using TypeScript with Node
Now a days, most of the REST API invokes with serverless backend. It is next generation compute service offered by many cloud providers. In this article I am going to describe how you can configure serverless backend to upload a file into AWS S3 bucket. We are going to build REST API with serverless approach using AWS Lambda. AWS Lambda is an event-driven, serverless computing platform that executes your code in response to events. It manages the underlying infrastructure scaling it up or down to meet the event rate.
In previous article, I have demonstrated How to upload a file using TypeScript with Node and Express. If you have not checked this out, I would recommended to check this one.
How to configure serverless backend using TypeScript with Node
Well, definetly you need to do some setup to get the serverless approach. And I also have made one article Create serverless REST API using AWS Lambda API Gateway RDS postgres with Nodejs and Typescript, please check this out to configure serverless framework with your TypeScript with Node code.
So we are going to use the following component to upload file into S3.
- AWS API Gateway
- AWS CloudFormation
- AWS Lambda
For serverless configuration, we first need to update the serverless.yml file. In this file we are definig the route of the method.
Next you need to create the handler.ts file and there you need to create a function like below
As we are going to upload the file (here it is an image) using multipart/form-data to you do need to have form data parser to handle the content type multipart/form-data. Let's create the form-data parser. We are going to use busboy to handle the streaming data. Busboy is a streaming parser for HTML form data for node.js. We are going to leverage this functionality here to upload files.
Now you are done with your setup. You can execute the code by running - npm run start-offline also you can deploy the code as a lambda function by running npm run deploy command and upload file the file from postman. Don't forget to select content type as miltipart/form-data and browse the image using file type like below -
You can find the complete code from here. If you have found this article useful, share this article with your friends and leave comment if you have any question. Your responses are also highly appreciated.