Using AWS Lambda and function URLs for webhooks

Using AWS Lambda and function URLs for webhooks

Hey there,

Today I wanted to highlight a cool little thing for Lambdas that is often overlooked or missed. The usual route to expose your lambda functions is to put them behind an API Gateway. But there's a quicker route when all you want is to make the Lambda take a webhook request or something similar.

Take GitHub for instance, maybe you want to send all events of a repository to a webhook: Your Lambda for instance and from there the sky is the limit.
Put all events into an EventBus and consume them somewhere down the line. Or provision a GitHub action runner on demand when an event for a workflow run comes in.

With function-urls, we only need to provision a lambda. The infrastructure code for this is sleek and easy. You cannot control the function URL you are getting though, the URL is random, but for webhooks, like you'd use for your GitHub repo this seems good enough. Security via obscurity.

An example in CDK

Let's look at a compact example of how this looks in action using CDK.

    import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';    
    ...

    const webhook = new NodejsFunction(this, 'webhook', {
      entry: './src/webhook.ts',
      environment: {
        WEBHOOK_SECRET: "super-secure-secret"
      },
    });
    const { url } = webhook.addFunctionUrl({
      authType: lambda.FunctionUrlAuthType.NONE,
    });
    new CfnOutput(this, 'functionUrl', {
      value: url,
    });

We use the NodeJsFunction construct to enable an easy way to define our lambda function in TypeScript. According to this definition, our CDK script expects our lambda code to be at src/webhook.ts.
The most relevant parts for our function URL example are below the NodejsFunction definition:
Our LambdaFunction instance in the variable webhook has a method that allows us to add a function URL to the lambda. We are defining the authType to be NONE, else we will run into problems because by default our function URL would require IAM auth.

The CfnOutput will hold our function URL and return it upon deployment.
This function URL can then be used, for example in GitHub as your webhook-URL.

I added a WEBHOOK_SECRET environment variable, but I'll leave the implementation of that to you.

Setting the function URL in the AWS Console

When you are not yet using the AWS CDK, you can easily enable a function URL for your lambda by going to the configuration tab and selecting Function URL and then Create function URL. Please keep in mind to set the authentication to NONE if you want to use it as a webhook url.

I hope you are as excited as me to learn about function URLs, and do let me know what you are planning to use them for.