DEV Community

Jay Dobariya
Jay Dobariya

Posted on

Add Custom Header in Website using Lambda@Edge

Lambda@Edge is a powerful serverless computing service provided by Amazon Web Services (AWS) that allows users to run custom code at the edge of the AWS global network, where their content is cached and served to users. With Lambda@Edge, users can add custom logic to their CloudFront distributions, such as modifying headers, redirecting requests, and manipulating requests and responses in real-time. In this blog, we will explore how to use Lambda@Edge with an example and code snippet.


Example Use Case:

Suppose you have a website hosted on S3 and served through CloudFront. You want to add a custom header to all requests that pass through CloudFront to track the source of the request. You can achieve this by creating a Lambda function and attaching it to your CloudFront distribution using Lambda@Edge.


Step 1: Create a Lambda Function
First, you need to create a Lambda function that adds the custom header to incoming requests. Here's a sample code snippet in Node.js:

exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
request.headers['X-Source'] = [{key: 'X-Source', value: 'CloudFront'}];
callback(null, request);
};

This code adds the X-Source header to the incoming request with the value CloudFront.


Step 2: Create a CloudFront Distribution
Next, you need to create a CloudFront distribution for your S3 bucket. In the CloudFront console, create a new distribution and select the S3 bucket as the origin.


Step 3: Add Lambda Function to CloudFront Distribution
After you have created the CloudFront distribution, go to the Behaviors tab and select the default behavior. Under Lambda Function Associations, select "Origin Request" and choose the Lambda function that you created in Step 1.


Step 4: Test the CloudFront Distribution
Once the CloudFront distribution has been updated with the Lambda function, you can test it by accessing your website through the CloudFront domain name. Use the browser's developer tools to inspect the incoming request headers, and you should see the X-Source header with the value CloudFront.


Conclusion:
Lambda@Edge provides a powerful way to add custom logic to your CloudFront distributions, enabling you to modify requests and responses in real-time. In this example, we showed how to add a custom header to all incoming requests using a Lambda function. This is just one of the many ways you can use Lambda@Edge to enhance the functionality of your CloudFront distributions.

Top comments (0)