Moving Static Assets Out of Lambda Functions
With serverless applications, it’s much more usual to put static assets somewhere for clients to fetch them directly, for example on S3. In fact, this is so common that S3 can pretend to be a web server. It even offers some basic web serving features out of the box, such as redirects and customising response headers. Browsers can directly load files from S3 using HTTPS.
In the previous chapters, you uploaded private files to S3 and generated temporary security grants for browsers to download them. You can also upload public files, and client devices will be able to access them without a particular temporary grant. There will be no need to involve a Lambda function in the process at all. That way, you only need to pay for data transfer for static assets. This is significantly cheaper than adding another API call and a function execution. Users will also get faster responses. It will be better for everyone.
For high-traffic applications, it’s usual to put a content distribution network (CDN) between users and S3 files, making the application even faster. AWS has a CDN called CloudFront, which can cache static files from S3 all over the world and even compress them automatically before sending them to users. CloudFront can also run Lambda functions to perform some quick business logic such as transforming responses or modifying incoming or outgoing headers. For your simple application, this would be unnecessary, so you’ll just use S3 directly.
Let’s restructure the application to look as in the figure given below. The client can load static assets directly from S3 without going through Lambda. A single API operation should send back both upload and download signatures, and client code can take over the remaining coordination tasks.