LoginSignup
1
0

AWS CDKでLambda Function URLsを試したい

Posted at

概要

  • AWS CDKでAPI Gateway + Lambdaの構成を作ったことは何度かあったのですが、Lambda Function URLsを試したことがなかったのでやってみました。
  • 前提条件
    • CDK v2
    • Node.js v18.18.2
    • TypeScript v5.3.2

Lambda Function URLs(Lambda 関数 URL)とは

Lambdaをhttpsから実行するには、API Gateway + Lambdaの構成にしてエンドポイントを作成することがよくありますが、Function URLsではLambdaがエンドポイントを作成してくれます。

API GatewayとLambda Function URLsの違い

簡単にいうと、API Gatewayの方が複雑な設定ができます。
API Gatewayでできることとして例えば、、

  • httpsだけでなくwebsocketをサポートしている
  • カスタムドメインが設定可能
  • API Keyで認証できる

単純にLambdaをhttpsから実行したいだけであれば、Lambda Function URLsの方が簡単に設定することができます。

また、API Gatewayの最大のタイムアウト時間は29秒ですが、Lambda Function URLsの場合はタイムアウトはなく、Lambda関数のタイムアウト(最大15分)という制限になるので、Lambda関数の実行時間が長くてAPI Gatewayでタイムアウトしてしまうような処理はLambda Function URLsを使うと良いかもしれません。

やってみる

まずは公式のドキュメントの通りにcdk initします。

mkdir test-project
cd test-project
cdk init app --language typescript

cdk initできたので、リソースの定義をしていきます。

import * as cdk from "aws-cdk-lib";
import {
  Function,
  Runtime,
  Code,
  FunctionUrlAuthType,
} from "aws-cdk-lib/aws-lambda";
import { Construct } from "constructs";

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

    // Function
    const fn = new Function(this, "MyFunction", {
      runtime: Runtime.NODEJS_18_X,
      handler: "index.handler",
      code: Code.fromAsset("./src"),
    });

    // Function URL
    const fnUrl = fn.addFunctionUrl({
      authType: FunctionUrlAuthType.NONE,
    });
  }
}

addFunctionUrl()でFunction URLsを設定します。
authTypeはデフォルトではAWS_IAMなので、今回はNONEにします。

関数の中身も書きます。適当にHello worldを返すだけの関数にします。

export const handler = async () => {
  return "Hello World";
};

これでFunction URLsが作成され、Hello worldが返ってきました。やったね🥺

ちなみに、authorizationというヘッダやクエリパラメータはをつけたらこのように取得できます。

  // headers受け取り
  const header1 = event.headers.header1;
  const header2 = event.headers.header2;
  // クエリパラメータ受け取り
  const param1 = event.queryStringParameters.param1;
  const param2 = event.queryStringParameters.param2;

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0