banner

KuchBhiLearning - A free website to learn and code

This is a good learning site. This contains details of cloud computing, AWS, AWS-CDK, AWS-SDK codes and examples including S3, Redis, lambda, api-gateway, cloudfront, cloudformation.

 Pass query params from cloudfront to api gateway

We have a setup where we have api gateway and cloudfront distribution in front.

You can setup cloudfront distribution along with s3 bucket here.

Extending the same example if there is a scenario where we need to pass the query string params to api gateway then we need to setup the origin request policy.

import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudFront from 'aws-cdk-lib/aws-cloudfront';
import * as cloudFrontOrigins from 'aws-cdk-lib/aws-cloudfront-origins';
 
const s3BucketWeb = new s3.Bucket(stack, `s3-web`, {
    // Block all public access
    blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    // When stack is deleted, delete this bucket also
    removalPolicy: cdk.RemovalPolicy.DESTROY,
    // Delete contained objects when bucket is deleted
    autoDeleteObjects: true
  });

  const originRequestPolicy = new cloudFront.OriginRequestPolicy(
    stack,
    `cf-origin-req-policy`,
    {
      cookieBehavior: cloudFront.OriginRequestCookieBehavior.all(),
      headerBehavior: cloudFront.OriginRequestHeaderBehavior.none(),
      queryStringBehavior: cloudFront.OriginRequestQueryStringBehavior.all(),
    }
  );


  let s3origin = new cloudFrontOrigins.S3Origin(s3BucketWeb);

  const cloudFrontDistribution = new cloudFront.Distribution(stack, `cloudfront-example`, {
    // Default path pointing to S3 Web Bucket where static content resides
    defaultBehavior: {
      // Point to S3 Web Bucket as origin
      origin: s3origin,
      // HTTP requests will be redirected to HTTPS
      viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      // Only allow GET, HEAD, OPTIONS methods
      allowedMethods: cloudFront.AllowedMethods.ALLOW_GET_HEAD_OPTIONS,
      // Cache GET, HEAD, OPTIONS
      cachedMethods: cloudFront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
      originRequestPolicy,
    },
  });


  cloudFrontDistribution.addBehavior('/test', s3origin, {
    viewerProtocolPolicy: cloudFront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    // Allow all methods for REST API endpoints
    allowedMethods: cloudFront.AllowedMethods.ALLOW_ALL,
    cachePolicy: cloudFront.CachePolicy.CACHING_DISABLED,
    originRequestPolicy,
  });

Origin request policy let's you create the cache policy and ensure the cookies and query string are being passed.

In case of S3 origin you can create your specific origin like api gateway.

No comments:

Post a Comment

If you have any doubts, Please let me know

Copyright 2022, KuchBhiLearning - A free website to learn and code. All rights Reserved.
| Designed by Yaseen Shariff