Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS CDK passing API Gateway URL to static site in same Stack

I'm trying to deploy an S3 static website and API gateway/lambda in a single stack.

The javascript in the S3 static site calls the lambda to populate an HTML list but it needs to know the API Gateway URL for the lambda integration.

Currently, I generate a RestApi like so...

    const handler = new lambda.Function(this, "TestHandler", {
      runtime: lambda.Runtime.NODEJS_10_X,
      code: lambda.Code.asset("build/test-service"),
      handler: "index.handler",
      environment: {
      }
    });

    this.api = new apigateway.RestApi(this, "test-api", {
      restApiName: "Test Service"
    });    

    const getIntegration = new apigateway.LambdaIntegration(handler, {
      requestTemplates: { "application/json": '{ "statusCode": "200" }' }
    });

    const apiUrl = this.api.url;

But on cdk deploy, apiUrl =

"https://${Token[TOKEN.39]}.execute-api.${Token[AWS::Region.4]}.${Token[AWS::URLSuffix.1]}/${Token[TOKEN.45]}/"

So the url is not parsed/generated until after the static site requires the value.

How can I calculate/find/fetch the API Gateway URL and update the javascript on cdk deploy?

Or is there a better way to do this? i.e. is there a graceful way for the static javascript to retrieve a lambda api gateway url?

Thanks.

like image 842
Tim Avatar asked Dec 10 '25 02:12

Tim


1 Answers

The pattern I've used successfully is to put a CloudFront distribution or an API Gateway in front of the S3 bucket.

So requests to https://[api-gw]/**/* are proxied to https://[s3-bucket]/**/*.

Then I will create a new Proxy path in the same API gateway, for the route called /config which is a standard Lambda-backed API endpoint, where I can return all sorts of things like branding information or API keys to the frontend, whenever the frontend calls GET /config.

Also, this avoids issues like CORS, because both origins are the same (the API Gateway domain).

With CloudFront distribution instead of an API Gateway, it's pretty much the same, except you use the CloudFront distribution's "origin" configuration instead of paths and methods.

like image 61
Dzhuneyt Avatar answered Dec 12 '25 19:12

Dzhuneyt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!