# AWS

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

This tutorial show you how to configure the Express application written with Ts.ED, to be executed as aAWS 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 ServerLoader configuration,
  • One for aws, named lambda.ts (the entry point on AWS Lambda, that 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 {ServerLoader, ServerSettings} from "@tsed/common";

@ServerSettings({
  port: 3000,
  rootDir: __dirname
})
export class Server extends ServerLoader {
  $beforeRoutesInit() {

    const cookieParser = require("cookie-parser"),
      bodyParser = require("body-parser"),
      compress = require("compression"),
      methodOverride = require("method-override"),
      cors = require("cors"),
      compression = require("compression"),
      awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");

    this
      .use(compression())
      .use(cors())
      .use(cookieParser())
      .use(compress({}))
      .use(methodOverride())
      .use(bodyParser.json())
      .use(bodyParser.urlencoded({
        extended: true
      }))

    this.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

Then create the lambda.ts:

import {ServerLoader} from "@tsed/common";
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, done: any) => {
  const server = await ServerLoader.bootstrap(Server);
  const lambdaServer = awsServerlessExpress.createServer(server.expressApp);

  awsServerlessExpress.proxy(lambdaServer, event, context);

  done();
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14

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

import {$log, ServerLoader} from "@tsed/common";
import {Server} from "./Server";

async function bootstrap() {
  try {
    $log.debug("Start server...");
    const server = await ServerLoader.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

TIP

You can find a project example with AWS configurattion here.

Example

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

Credits

Thanks to vetras for his contribution.