Lambda functions provide a way for you to run your code in the AWS cloud without having to manage servers, software, networking, or infrastructure. You are only responsible for our code, and you only pay for when your code runs. This can greatly reduce the total ownership cost, both financially and temporally, of your application, but there can be some “gotchas” that you should consider before you start writing your first lambda. First is dependencies. Lambda supports multiple language runtimes – the two most common being Node.js and Python. Both languages offer robust third party package libraries through npm and pip3, respectively. However, Lambda does not offer access any other packages out of the box (only including aws-sdk in the case of Node.js or boto3 with Python, both to access AWS services), so if you wish to include packages with your software you will have to download them locally, and package them in a zip file and upload it to Lambda. If your package contains more than 10MB of libraries, you will not be able to use the console code editor and will need to edit locally with an IDE.
To call your Lambda code you can connect it to all sorts of AWS triggers, like CloudWatch Event Bridge Buses, S3 upload triggers, and more. But the most common is to call your code with parameters through a URL, and this can be achieved through connecting it to an API gateway, or a function URL, which is relatively new. Function URLs are automatically generated URLs that provide an endpoint to your Lambda, but do not offer much flexibility compared to API gateways, which let you configure resources, routes, authorization, Lambda authorizers, custom domains, and more. When connected to an API gateway, you can configure Lambda Proxy mode where your direct responses correlate to HTTP responses to the browser like this:
return {
“statusCode”: 200,
“headers”: {
“Content-Type”: “application/json”,
“Access-Control-Allow-Origin”: “*”, // Required for CORS support to work
“Access-Control-Allow-Credentials”: true // Required for cookies, authorization headers with HTTPS
},
“body”: “{\”message\”: \”Hello, world!\”}”
}
This gives you direct access to set whatever HTTP status code you want, say a 302 redirect, but this comes to the second pitfall – if you want to display a page during the redirect, you are not able to. You are only allowed to return Location and Set-Cookie headers. Anything else isn’t just ignored, you will get a 502 hard fail.