Angular Server Side Rendering on AWS Lambda

This is an example of Angular Universal app running on AWS Lambda.
The finished sample code: jhmt/ng-ssr-on-aws-lambda

Prerequesites

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

  1. Move “server.ts” and “webpack.server.config.js” in another folder (e.g. “/ssr”)
  2. Split the “listen” block into the new file to start in order to reuse the app on AWS Lambda.
  3. Modify “webpack:server” script in “package.json” to find the moved webpack file.
  4. Make sure “npm run build:ssr” works fine.

Initialize Serverless

  1. create “serverless.yml” file.
    serverless create --template aws-nodejs --name ng-ssr-aws-lambda
    

Create Lambda entry point

  1. create a new folder to store lambda function handler and webpack config (e.g. “lambda”)
  2. create a handler file (e.g. index.ts)
  3. create a webpack config file.

Modify serverless.yml file

  1. 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"
   ]