This is an example of Angular Universal app running on AWS Lambda.
The finished sample code: jhmt/ng-ssr-on-aws-lambda
Prerequesites
- Node.js (version 6.9.1 or upper)
- AWS account (for deploying to AWS Lambda)
- Serverless framework installed
- AWS Credentials
Used frameworks/technologies
How does AWS Lambda render html?
Angular Universal works as a middleware for web server frameworks.
e.g. Express, Hapi and ASP.NET.
Meanwhile, an Express app can work on AWS Lambda with using “aws-serverless-express” node module provided by AWS. In this sample, AWS Lambda renders html with aws-serverless-express and Angular Express Engine.
Clone and run universal-starter
git clone https://github.com/angular/universal-starter.git
Prepare deploy
- Move “server.ts” and “webpack.server.config.js” in another folder (e.g. “/ssr”)
- Split the “listen” block into the new file to start in order to reuse the app on AWS Lambda.
- Modify “webpack:server” script in “package.json” to find the moved webpack file.
- Make sure “npm run build:ssr” works fine.
Initialize Serverless
- create “serverless.yml” file.
serverless create --template aws-nodejs --name ng-ssr-aws-lambda
Create Lambda entry point
- create a new folder to store lambda function handler and webpack config (e.g. “lambda”)
- create a handler file (e.g. index.ts)
- create a webpack config file.
Modify serverless.yml file
- modify to route GET services to “lambda” folder
service: ng-ssr-aws-lambda provider: name: aws runtime: nodejs6.10 region: ap-southeast-2 memorySize: 128 plugins: - serverless-webpack custom: webpack: lambda/webpack.config.js functions: main: handler: lambda/index.handler events: - http: path: / method: get - http: path: "{proxy+}" method: get
Deploy
Make sure your AWS credentials have been set before deploy -
Serverless Framework - AWS Lambda Guide - Credentials
"npm run build:ssr && serverless deploy"If you got the errors of "TS2304: Cannot find name 'AsyncIterator' or TS2304: Cannot find name 'AsyncIterable'", add the following in "tsconfig.json"
"lib": [ "es2017", "dom", "esnext.asynciterable" ]