I Tried Making Network Calls with Amazon CloudFront Functions

I Tried Making Network Calls with Amazon CloudFront Functions

Amazon CloudFront Functions now lets functions call origins via cf.fetch() and cf.beacon(). I try reading config, authorization, and sending events, using S3 with OAC and a Lambda function URL as destinations.
2026.11.19

This page has been translated by machine translation. View original

Introduction

On November 18, 2026, CloudFront Functions gained support for network calls, allowing you to call external APIs and other endpoints with cf.fetch() and cf.beacon().

https://aws.amazon.com/jp/about-aws/whats-new/2026/11/cloudfront-functions-network-calls/

cf.fetch() is a method that sends a request to an origin and receives the response. A function can call an API endpoint and use its response to decide how to handle the request. For example, you can use it in the following ways:

  • Check an AI agent's permissions and usage budget, and deliver only approved requests to an API or MCP server
  • Send request signals to a security service or fraud detection service, and block or verify fraudulent traffic

cf.beacon() is a method that sends a request without waiting for the response. Even for content served from the cache, you can send analytics events in the background without delaying the response to the viewer.

This article presents the results of trying cf.fetch() and cf.beacon() with an S3 bucket configured with OAC and a Lambda function URL as origins.

Test Configuration

The destination of cf.fetch() and cf.beacon() is specified by the ID and path of an origin registered in the same distribution.

The distribution in this article has two origins: s3-config for S3 and auth-api for the Lambda function URL. The correspondence between behaviors and functions is as follows.

Behavior Behavior's origin Associated function Origin the function calls
Default s3-config t1-response (viewer response) s3-config
/t2/* s3-config t2-auth (viewer request) auth-api
/t3/* s3-config t3-beacon (viewer request) auth-api

Preparing the Origins

Place the following objects to be returned during the test in the S3 bucket.

Key Content
config/experiments.json The JSON shown later in "S3 Configuration File"
index.html hello
t2/ok.txt ok-body
t3/page.txt cached page
Commands to create the S3 bucket and objects
aws s3api create-bucket --bucket amzn-s3-demo-bucket --create-bucket-configuration LocationConstraint=ap-northeast-1
aws s3api put-object --bucket amzn-s3-demo-bucket --key config/experiments.json --body experiments.json --content-type application/json
aws s3api put-object --bucket amzn-s3-demo-bucket --key index.html --body index.html --content-type text/html
aws s3api put-object --bucket amzn-s3-demo-bucket --key t3/page.txt --body page.txt --content-type text/plain
aws s3api put-object --bucket amzn-s3-demo-bucket --key t2/ok.txt --body t2-ok.txt --content-type text/plain

As the receiving side, prepare one Lambda function with a function URL (hereafter referred to as the "receiver Lambda"). This function serves both as the authorization API (/auth) and the beacon receiver (/beacon).

Code and creation commands for the receiver Lambda

index.mjs:

// 検証用の受け側。認可 API と beacon 受信を1つの関数 URL で兼ねる。
const json = (status, body, extra = {}) => ({
  statusCode: status,
  headers: { 'content-type': 'application/json', ...extra },
  body: JSON.stringify(body),
});

export const handler = async (event) => {
  const method = event.requestContext.http.method;
  const path = event.rawPath;
  const query = event.rawQueryString || '';
  const headers = event.headers || {};
  const body = event.body
    ? event.isBase64Encoded
      ? Buffer.from(event.body, 'base64').toString('utf8')
      : event.body
    : '';

  // 受け側で何が届いたかを CloudWatch Logs に残す
  console.log(
    'RECV ' +
      JSON.stringify({
        method,
        path,
        query,
        sha256: headers['x-amz-content-sha256'] || null,
        bodyLength: body.length,
      }),
  );

  if (path === '/auth' && method === 'POST') {
    const parsed = JSON.parse(body);
    const token = String(parsed.token || '');
    if (token.endsWith('ok')) return json(200, { userId: 'u-123' });
    if (token.endsWith('deny')) return json(403, { error: 'forbidden' });
    return json(401, { error: 'unknown token' });
  }

  if (path === '/beacon') {
    console.log('BEACON ' + JSON.stringify({ method, query, body }));
    return json(200, { received: true });
  }

  return json(404, { error: 'not found' });
};

Zip index.mjs and save it as function.zip. Create the execution role with a policy that trusts Lambda (trust.json), attach AWSLambdaBasicExecutionRole, and then create the function.

trust.json:

{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
aws iam create-role --role-name devio1119-cff-lambda-role --assume-role-policy-document file://trust.json
aws iam attach-role-policy --role-name devio1119-cff-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws lambda create-function --function-name devio1119-cff-api --runtime nodejs22.x --handler index.handler --role arn:aws:iam::<ACCOUNT_ID>:role/devio1119-cff-lambda-role --zip-file fileb://function.zip --timeout 10 --architectures arm64

s3-config is configured with S3 and OAC, and auth-api with the Lambda function URL and OAC. Create one OAC each for S3 and Lambda, and create a function URL with the AWS_IAM authentication type for the Lambda function.

Commands to create the OACs and function URL
aws cloudfront create-origin-access-control --origin-access-control-config Name=devio1119-cff-s3\,SigningProtocol=sigv4\,SigningBehavior=always\,OriginAccessControlOriginType=s3
aws cloudfront create-origin-access-control --origin-access-control-config Name=devio1119-cff-lambda\,SigningProtocol=sigv4\,SigningBehavior=always\,OriginAccessControlOriginType=lambda
aws lambda create-function-url-config --function-name devio1119-cff-api --auth-type AWS_IAM

Creating and Associating the Functions

Create and publish the functions with JavaScript runtime 2.0 (cloudfront-js-2.0). This article uses t1-response, which reads the configuration; t2-auth, which handles authorization; and t3-beacon, which sends beacons. The following commands are an example for t1-response; the other functions are created with the same steps.

aws cloudfront create-function --name devio1119-t1-response --function-config Comment=devio1119\ t1-response\,Runtime=cloudfront-js-2.0 --function-code fileb://t1-response.js
aws cloudfront publish-function --name devio1119-t1-response --if-match <ETag>

Associate the published functions with the distribution's behaviors. For the default behavior, associate t1-response with viewer response.

Distribution settings
aws cloudfront create-distribution --distribution-config file://distribution-config.json

distribution-config.json:

{
  "CallerReference": "devio1119-1795052864",
  "Comment": "devio1119 cloudfront functions network calls",
  "Enabled": true,
  "DefaultRootObject": "index.html",
  "PriceClass": "PriceClass_200",
  "HttpVersion": "http2",
  "Origins": {
    "Quantity": 2,
    "Items": [
      {
        "Id": "s3-config",
        "DomainName": "amzn-s3-demo-bucket.s3.ap-northeast-1.amazonaws.com",
        "OriginAccessControlId": "<S3_OAC_ID>",
        "S3OriginConfig": {
          "OriginAccessIdentity": ""
        }
      },
      {
        "Id": "auth-api",
        "DomainName": "<FUNCTION_URL_ID>.lambda-url.ap-northeast-1.on.aws",
        "OriginAccessControlId": "<LAMBDA_OAC_ID>",
        "CustomOriginConfig": {
          "HTTPPort": 80,
          "HTTPSPort": 443,
          "OriginProtocolPolicy": "https-only",
          "OriginSslProtocols": {
            "Quantity": 1,
            "Items": [
              "TLSv1.2"
            ]
          }
        }
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "s3-config",
    "ViewerProtocolPolicy": "https-only",
    "AllowedMethods": {
      "Quantity": 2,
      "Items": [
        "GET",
        "HEAD"
      ]
    },
    "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
    "Compress": true,
    "FunctionAssociations": {
      "Quantity": 1,
      "Items": [
        {
          "EventType": "viewer-response",
          "FunctionARN": "arn:aws:cloudfront::<ACCOUNT_ID>:function/devio1119-t1-response"
        }
      ]
    }
  },
  "CacheBehaviors": {
    "Quantity": 2,
    "Items": [
      {
        "TargetOriginId": "s3-config",
        "ViewerProtocolPolicy": "https-only",
        "AllowedMethods": {
          "Quantity": 2,
          "Items": [
            "GET",
            "HEAD"
          ]
        },
        "CachePolicyId": "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
        "Compress": true,
        "FunctionAssociations": {
          "Quantity": 1,
          "Items": [
            {
              "EventType": "viewer-request",
              "FunctionARN": "arn:aws:cloudfront::<ACCOUNT_ID>:function/devio1119-t2-auth"
            }
          ]
        },
        "PathPattern": "/t2/*"
      },
      {
        "TargetOriginId": "s3-config",
        "ViewerProtocolPolicy": "https-only",
        "AllowedMethods": {
          "Quantity": 2,
          "Items": [
            "GET",
            "HEAD"
          ]
        },
        "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
        "Compress": true,
        "FunctionAssociations": {
          "Quantity": 1,
          "Items": [
            {
              "EventType": "viewer-request",
              "FunctionARN": "arn:aws:cloudfront::<ACCOUNT_ID>:function/devio1119-t3-beacon"
            }
          ]
        },
        "PathPattern": "/t3/*"
      }
    ]
  }
}

After creating the distribution, use the distribution ID from the output of create-distribution as the condition to set the bucket policy and the Lambda permissions.

Bucket policy and Lambda permissions

bucket-policy.json:

{"Version":"2012-10-17","Statement":[{"Sid":"AllowCloudFrontServicePrincipal","Effect":"Allow","Principal":{"Service":"cloudfront.amazonaws.com"},"Action":"s3:GetObject","Resource":"arn:aws:s3:::amzn-s3-demo-bucket/*","Condition":{"StringEquals":{"AWS:SourceArn":"arn:aws:cloudfront::<ACCOUNT_ID>:distribution/<DISTRIBUTION_ID>"}}}]}
aws s3api put-bucket-policy --bucket amzn-s3-demo-bucket --policy file://bucket-policy.json
aws lambda add-permission --function-name devio1119-cff-api --statement-id AllowCloudFrontInvokeFunctionUrl --action lambda:InvokeFunctionUrl --principal cloudfront.amazonaws.com --source-arn arn:aws:cloudfront::<ACCOUNT_ID>:distribution/<DISTRIBUTION_ID> --function-url-auth-type AWS_IAM
aws lambda add-permission --function-name devio1119-cff-api --statement-id AllowCloudFrontInvokeFunction --action lambda:InvokeFunction --principal cloudfront.amazonaws.com --source-arn arn:aws:cloudfront::<ACCOUNT_ID>:distribution/<DISTRIBUTION_ID>

cf.fetch()

S3 Configuration File

Place the following JSON at config/experiments.json in S3.

{"activeExperiment":"exp-blue-2026"}

The viewer response function reads this JSON with cf.fetch() and adds the value of activeExperiment to the x-experiment response header.

import cf from 'cloudfront';

async function handler(event) {
  const response = event.response;
  const r = await cf.fetch('/config/experiments.json', {
    originId: 's3-config',
    includeBody: true,
  });
  if (r.ok) {
    const config = await r.json();
    response.headers['x-experiment'] = { value: config.activeExperiment };
  }
  return response;
}

x-experiment is added to the response the client receives.

$ curl -sS -i https://d111111abcdef8.cloudfront.net/\?r=2
HTTP/2 200 
x-experiment: exp-blue-2026
x-cache: Miss from cloudfront

hello

Lambda Function URL Authorization API

The authorization function (t2-auth) converts the value of the Authorization header into JSON and POSTs it to the authorization API (/auth). If the response is 2xx, it lets the request through; otherwise, it returns 403.

import cf from 'cloudfront';
const crypto = require('crypto');

async function handler(event) {
  const request = event.request;
  const auth = request.headers['authorization'];
  if (!auth) {
    return { statusCode: 401, statusDescription: 'Unauthorized' };
  }

  const body = JSON.stringify({ token: auth.value, uri: request.uri });
  const headers = { 'content-type': 'application/json' };
  // Lambda 関数 URL への POST は、本文の SHA-256 を関数側で付ける必要がある
  headers['x-amz-content-sha256'] = crypto.createHash('sha256').update(body).digest('hex');

  const response = await cf.fetch('/auth', {
    originId: 'auth-api',
    method: 'POST',
    headers: headers,
    body: body,
    includeBody: true,
  });
  if (!response.ok) {
    console.log('authorize returned ' + response.status);
    return {
      statusCode: 403,
      statusDescription: 'Forbidden',
      headers: { 'x-fn-authorize-status': { value: String(response.status) } },
    };
  }
  const result = await response.json();
  request.headers['x-user-id'] = { value: result.userId };
  return request;
}

The receiver Lambda returns different responses depending on whether the token ends with ok or deny. Associate t2-auth with the viewer request of /t2/*, and send requests with curl while changing the Authorization header, as follows.

curl -i -H 'Authorization: Bearer abc-ok' https://d111111abcdef8.cloudfront.net/t2/ok.txt
Input (Authorization header) Authorization API response Response to the client
No header Not called 401
Bearer abc-ok 200 200, body ok-body
Bearer abc-deny 403 403, x-fn-authorize-status: 403

When POSTing to a Lambda function URL with a body, the function must calculate the SHA-256 of the body and put it in the x-amz-content-sha256 header.

cf.beacon()

Sending Beacons

Associate the following function with the viewer request of /t3/*. The function calls cf.beacon() without await. ?mode= switches the beacon method, and ?id= is used to match against the receiver's logs.

import cf from 'cloudfront';
const crypto = require('crypto');

// ?mode= で beacon のメソッドを切り替える
//   post : POST + x-amz-content-sha256 つき
//   get  : 本文なしの GET
// ?id= は受け側のログと突き合わせるための印
function handler(event) {
  const request = event.request;
  const qs = request.querystring;
  const mode = qs.mode ? qs.mode.value : 'post';
  const id = qs.id ? qs.id.value : 'none';

  if (mode === 'get') {
    cf.beacon('/beacon?id=' + id, {
      originId: 'auth-api',
    });
  } else {
    const body = JSON.stringify({ id: id, mode: mode, uri: request.uri });
    const headers = {
      'content-type': 'application/json',
      'x-amz-content-sha256': crypto.createHash('sha256').update(body).digest('hex'),
    };
    cf.beacon('/beacon', {
      originId: 'auth-api',
      method: 'POST',
      headers: headers,
      body: body,
    });
  }
  return request;
}

All requests from the client are GET. The POST in the table is the method that cf.beacon() in the function sends to the receiver.

Client request (query added to GET /t3/page.txt) Beacon method Did it reach the receiver Lambda?
?mode=post&id=m1 POST Arrived
?mode=get&id=g1 GET (no body) Arrived

In the receiver Lambda's log group /aws/lambda/devio1119-cff-api, you can check the received content in the BEACON lines.

BEACON {"method":"POST","query":"","body":"{\"id\":\"m1\",\"mode\":\"post\",\"uri\":\"/t3/page.txt\"}"}
BEACON {"method":"GET","query":"id=g1","body":""}

Summary

CloudFront Functions can now send HTTP requests to origins in the same distribution (except for the Free plan and multi-tenant distributions).

Only one network call can be made per function execution, the response can be awaited for up to 1 second, and the request body and response body are each limited to 10 KB. Give it a try if you need to customize authentication and authorization, or to obtain trace information.

Share this article

AWSのお困り事はクラスメソッドへ