Use the hit counter

Add a hit counter to our stack

Okay, our hit counter is ready. Let’s use it in our app. Open lib/cdk-workshop-stack.ts and add the following highlighted code:

import cdk = require('@aws-cdk/cdk');
import lambda = require('@aws-cdk/aws-lambda');
import apigw = require('@aws-cdk/aws-apigateway');
import { HitCounter } from './hitcounter';

export class CdkWorkshopStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const hello = new lambda.Function(this, 'HelloHandler', {
      runtime: lambda.Runtime.NodeJS810,
      code: lambda.Code.asset('lambda'),
      handler: 'hello.handler'

    const helloWithCounter = new HitCounter(this, 'HelloHitCounter', {
      downstream: hello

    // defines an API Gateway REST API resource backed by our "hello" function.
    new apigw.LambdaRestApi(this, 'Endpoint', {
      handler: helloWithCounter.handler

Notice that we changed our API Gateway handler to helloWithCounter.handler instead of hello. This basically means that whenever our endpoint is hit, API Gateway will route the request to our hit counter handler, which will log the hit and relay it over to the hello function. Then, the responses will be relayed back in the reverse order all the way to the user.


cdk deploy

And the output:

CdkWorkshopStack.Endpoint8024A810 =


Okay, ready to give this a go? (you should, again, see the URL of your API in the output of the “deploy” command).

Use curl or your web browser to hit your endpoint (we use -i to show HTTP response fields and status code):

curl -i

Oh no… seems like something went wrong:

HTTP/1.1 502 Bad Gateway

{"message": "Internal server error"}

Let’s see how to find out what happened and fix it.