Create Lambda@Edge function

Create Lambda@Edge function

In this section, you create a Lambda function that reads the viewer request headers and returns an HTML page directly from the edge.

Lambda@Edge functions must be created in US East (N. Virginia) us-east-1. Keep all other settings at their defaults: Lambda@Edge does not support ARM64, VPC access, environment variables, or layers.

Part 1 - Create the Lambda function

  1. In the AWS Management Console, check that the Region is United States (N. Virginia).

  2. Open the Lambda console. In the navigation pane, select Event Functions, then select Create Event Function.

CloudFront Lab

  1. On the Create Event Function page, configure:
    • Select Author from scratch.
    • Function name: LambdaEdgeImmersionDayLabFunction
    • Runtime: the latest Node.js version (the screenshot shows Node.js 26.x).

CloudFront Lab

  1. Expand Additional settings and configure the execution role:
    • Turn on Custom execution role.
    • In the Create role panel, under Permissions, select Automatic permissions.
    • Select Save, then select Create function at the bottom of the page.

CloudFront Lab

  1. The function is created.

CloudFront Lab

Part 2 - Allow Lambda@Edge to use the execution role

The automatically created role trusts only lambda.amazonaws.com. Lambda@Edge also requires edgelambda.amazonaws.com. If you skip this part, deploying to CloudFront in the next section fails.

  1. Select Configuration > Permissions, then select the role name under Execution role (the screenshot shows PowerUserRole; your role name may differ).

CloudFront Lab

  1. In IAM, select Trust relationships > Edit trust policy.

CloudFront Lab

  1. Replace the policy with the following JSON, then select Update policy:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com",
          "edgelambda.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

CloudFront Lab

  1. Return to the Lambda function browser tab.

Part 3 - Create a test event

  1. Select the Test tab and configure:
    • Test event action: Create new event
    • Invocation type: Synchronous (default)
    • Event name: TestEvent
    • Event sharing settings: Private (default)

CloudFront Lab

  1. In Event JSON, paste the JSON below. It simulates a CloudFront viewer request. Replace these values with your own resources:
Field Replace with
config.distributionDomainName and headers.host Your distribution domain name, for example dxxxxxxxxxxxxx.cloudfront.net
config.distributionId Your distribution ID
origin.custom.domainName Public DNS name of your EC2 origin
origin.s3.domainName Domain name of your secondary S3 bucket
{
  "Records": [
    {
      "cf": {
        "config": {
          "distributionDomainName": "d3lxmwqap7z3ev.cloudfront.net",
          "distributionId": "E9JUCODO1O8KE",
          "eventType": "viewer-request",
          "requestId": "4fteXTJJX96ttx8Q183UrP0UJ8QW1p5BcLBXPNISFXBqbh-T_Y33C_Cz"
        },
        "request": {
          "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334",
          "method": "GET",
          "querystring": "size=large",
          "uri": "/picture.jpg",
          "headers": {
            "host": [
              {
                "key": "Host",
                "value": "d3lxmwqap7z3ev.cloudfront.net"
              }
            ],
            "user-agent": [
              {
                "key": "User-Agent",
                "value": "curl/7.51.0"
              }
            ]
          },
          "origin": {
            "custom": {
              "customHeaders": {
                "my-origin-custom-header": [
                  {
                    "key": "My-Origin-Custom-Header",
                    "value": "Test"
                  }
                ]
              },
              "domainName": "ec2-44-214-179-242.compute-1.amazonaws.com",
              "keepaliveTimeout": 5,
              "path": "",
              "port": 80,
              "protocol": "http",
              "readTimeout": 5,
              "sslProtocols": [
                "TLSv1",
                "TLSv1.1"
              ]
            },
            "s3": {
              "authMethod": "none",
              "customHeaders": {
                "my-origin-custom-header": [
                  {
                    "key": "My-Origin-Custom-Header",
                    "value": "Test"
                  }
                ]
              },
              "domainName": "s3bucket-secondary-681990781993-us-east-1-an.s3.us-east-1.amazonaws.com",
              "path": "",
              "region": "us-east-1"
            }
          }
        }
      }
    }
  ]
}
  1. Select Save.

Part 4 - Return a simple HTML page

  1. Select the Code tab. Replace the content of index.js with the following code, which returns an HTML page showing the Host and User-Agent headers.
export const handler = async (event) => {
  console.log("Request Event:" + JSON.stringify(event, null, 2));

  const requestHeaders = event.Records[0].cf.request.headers;

  // Extract headers safely
  const userAgent = requestHeaders['user-agent']?.[0]?.value || 'Unknown';
  const host = requestHeaders['host']?.[0]?.value || 'Unknown';

  // Generate HTML content from request headers
  const htmlContent = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>Lambda@Edge Response</title>
      </head>
      <body>
        <h1>Hello from Lambda@Edge!</h1>
        <p><strong>Host:</strong> ${host}</p>
        <p><strong>User-Agent:</strong> ${userAgent}</p>
      </body>
    </html>
  `;

  // Return the response directly. CloudFront sends it to the viewer.
  return {
    status: '200',
    statusDescription: 'OK',
    headers: {
      'cache-control': [{
        key: 'Cache-Control',
        value: 'max-age=100'
      }],
      'content-type': [{
        key: 'Content-Type',
        value: 'text/html; charset=UTF-8'
      }],
    },
    body: htmlContent,
  };
};

CloudFront Lab

  1. Select Deploy (Ctrl+Shift+U), wait until the status shows Current, then select Test (Ctrl+Shift+I). If you test before deploying, Lambda runs the old code.

CloudFront Lab

  1. In the OUTPUT tab, the status is Succeeded and the response contains the HTTP 200 status, headers, and HTML body that CloudFront will return to the viewer.

CloudFront Lab

The same result also appears in the Test tab.

CloudFront Lab

  1. Scroll down to Function Logs. The Request Event log shows the event CloudFront passes to the function: cf.config (distribution details), cf.request (client IP, URI, headers), and cf.request.origin (origin details).

CloudFront Lab CloudFront Lab CloudFront Lab

Part 5 - Return the request headers as an HTML table

  1. Replace the code in index.js with the following code, which returns all request headers as an HTML table.
exports.handler = async (event) => {
  const requestHeaders = event.Records[0].cf.request.headers;
  
  let str = '<table border="1" width="100%">' +
            '<thead>' +
              '<tr><td><h1>Header</h1></td><td><h1>Value</h1></td></tr>' +
            '</thead>' +
            '<tbody>';

  for (const key of Object.keys(requestHeaders)) {
      str += '<tr><td>' + key + '</td><td>' + requestHeaders[key][0].value + '</td></tr>';
  }

  str += '</tbody></table>';

  const htmlContent = `
    <html lang="en">
      <body>
        <table border="1" width="100%">
          <thead>
            <tr><td><h1>Lambda@Edge Lab</h1></td></tr>
          </thead>
          <tfoot>
            <tr><td>Immersion Days - Edge Services - Module 3</td></tr>
          </tfoot>
          <tbody>
            <tr><td>Response sent by API</td></tr>
          </tbody>
          <tbody>
            <tr><td>${str}</td></tr>
          </tbody>
        </table>
      </body>
    </html>
  `;

  return {
    status: '200',
    statusDescription: 'OK',
    headers: {
      'cache-control': [{ key: 'Cache-Control', value: 'max-age=100' }],
      'content-type': [{ key: 'Content-Type', value: 'text/html; charset=UTF-8' }],
    },
    body: htmlContent,
  };
};
  1. Select Deploy (Ctrl+Shift+U), wait for Current, then select Test (Ctrl+Shift+I).

CloudFront Lab

  1. The body now contains a table with one row per request header.

CloudFront Lab

Part 6 - Publish a version

CloudFront can only use a numbered version (for example :1), not $LATEST. Publish a new version every time you change the code.

  1. Select the Versions tab, then select Publish new version.

CloudFront Lab

  1. In Version description, enter version 1, then select Publish.

CloudFront Lab

  1. Version 1 is created and its ARN ends with :1. You will use this version in the next section.

CloudFront Lab