# AWS

Amazon Web Services is one possible way to host your Node.js application.

This tutorial shows you how to configure the Express application written with Ts.ED, to be executed as an AWS Lambda Function.

More information here: Official AWS Docs

# Installation

First, install the aws-serverless-express module:

npm install --save aws-serverless-express
1

# Configuration

You need to create three files:

  • One for the Server configuration,
  • One for AWS, named lambda.ts (the entry point on AWS Lambda, which contains the function handler),
  • One for the local development, for example "index.js" (that you can use to run the app locally with ts-node local.ts)

Create the server and add the AWS middleware:

import {Configuration, Inject, PlatformApplication} from "@tsed/common";
import "@tsed/platform-express";
import * as bodyParser from "body-parser";
import * as compress from "compression";
import * as cookieParser from "cookie-parser";
import * as cors from "cors";
import * as methodOverride from "method-override";

const awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");

@Configuration({
  port: 3000,
  rootDir: __dirname
})
export class Server {
  @Inject()
  app: PlatformApplication;

  $beforeRoutesInit() {
    this.app
      .use(compress())
      .use(cors())
      .use(cookieParser())
      .use(compress({}))
      .use(methodOverride())
      .use(bodyParser.json())
      .use(bodyParser.urlencoded({
        extended: true
      }))
      .use(awsServerlessExpressMiddleware.eventContext());
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

Then create the lambda.ts:

import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server";

const awsServerlessExpress = require("aws-serverless-express");

// The function handler to setup on AWS Lambda console -- the name of this function must match the one configured on AWS
export const handler = async (event: any, context: any) => {
  const platform = await PlatformExpress.bootstrap(Server);
  const lambdaServer = awsServerlessExpress.createServer(platform.app.callback());

  return awsServerlessExpress.proxy(lambdaServer, event, context, "PROMISE").promise;
};
1
2
3
4
5
6
7
8
9
10
11
12

And finally create an index.ts to run your server in development mode:

import {$log} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server";

async function bootstrap() {
  try {
    $log.debug("Start server...");
    const server = await PlatformExpress.bootstrap(Server);

    await server.listen();
    $log.debug("Server initialized");
  } catch (er) {
    $log.error(er);
  }
}

bootstrap();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

TIP

You can find a project example with AWS configuration here.

Example

You can see an example provided by the AWS Team on this github repository.

Credits

Thanks to vetras for his contribution.