AWS Builder Center

Write Custom Data Directly to CloudFront Access Logs with CloudFront Functions

CloudFront Functions now provides the `cf.logCustomData()` helper method, which writes data such as A/B test assignments, authorization outcomes, and URL rewrite results to CloudFront access logs. This article explains the log fields, configuration steps, code examples, and how to query the data with Amazon Athena. The examples in this article demonstrate the relevant APIs and log fields. Adjust the configuration for your environment before deployment.

1. Introduction

CloudFront Functions run JavaScript at CloudFront edge locations. You can use them for URL rewrites, request header modifications, request routing, and simple authorization checks.
Previously, data written by function code with  console.log()  was sent to Amazon CloudWatch Logs, while request data such as status codes, cache hits, edge locations, and latency was stored in CloudFront access logs. Analyzing a function execution together with its request result required correlating two log sources.
Released on July 14, 2026,  cf.logCustomData()  writes custom data produced by a function to the CloudFront access log for the same request.

2. Existing Logging and the Change

2.1 Logging Before the Feature

This article covers two log types:
Log type
Content
How it is produced
CloudFront access logs
Request metadata such as the URI, status code, edge location, cache result, latency, and User-Agent
Automatically generated by CloudFront (real-time logs or standard logging (v2))
Amazon CloudWatch Logs
Custom content written by  console.log()  in the function
Explicitly written by CloudFront Functions
Before  cf.logCustomData()  was available, functions had to write custom output to Amazon CloudWatch Logs with  console.log() . An analysis workflow typically had to:
  1. Read the function output from Amazon CloudWatch Logs;
  1. Read the request result from CloudFront access logs;
  1. Correlate the two sources using request IDs, timestamps, or other fields.
This workflow required processing data across separate log systems.
Standard access logs also record cookies and query strings as complete fields. They do not automatically split a business parameter into a separate field:
  • Cookies: Cookie logging must be enabled, and  cs(Cookie)  contains the Cookie field rather than an individual business value.
  • Query strings:  cs-uri-query  contains the complete query string rather than separate  utm_source ,  gclid , or other parameter fields.
With  cf.logCustomData() , a function can extract the values it needs and write them to a dedicated log field. Downstream queries then need less field parsing.

2.2 Custom Log Fields

 cf.logCustomData()  accepts a string and writes it to a field based on the event to which the function is associated:
  • A Viewer Request function writes the data to the  viewer-request-log-data  field in the access log;
  • A Viewer Response function writes the data to the  viewer-response-log-data  field;
  • Both real-time logs and standard logging (v2) support these fields.
The custom data and request result are stored in the same access log record, so a query can use them together.

3. Architecture

The following diagram shows standard logging (v2) delivered to Amazon S3 and real-time logs delivered to Amazon Kinesis Data Streams:
┌─────────────────────────────────────────┐
Viewer ──────► │ CloudFront edge location │
(request) │ │
│ ┌────────────────────────────────────┐ │
│ │ Viewer Request Function │ │
│ │ - Make decisions (A/B, auth, route)│──┼──┐
│ │ - cf.logCustomData("...") │ │ │
│ └────────────────────────────────────┘ │ │
│ │ │ │
│ ▼ │ │
│ Origin / cache response │ │
│ │ │ │
│ ┌────────────────────────────────────┐ │ │
│ │ Viewer Response Function (optional)│ │ │
│ │ - cf.logCustomData("...") │──┼──┤
│ └────────────────────────────────────┘ │ │
└─────────────────────────────────────────┘ │
│ │
Custom data is merged into the same access ◄┘
log record
│
┌─────────────────────────┴─────────────────────────┐
▼ ▼
┌──────────────────┐ ┌──────────────────────┐
│ Standard logging │ │ Real-time logs │
│ (for example, S3)│ │ (Kinesis Data │
│ │ │ Streams) │
└──────────────────┘ └──────────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────────┐
│ Amazon Athena │ │ Near-real-time │
│ (batch analysis) │ │ consumption / alerts │
└──────────────────┘ └──────────────────────┘
 console.log()  still writes to Amazon CloudWatch Logs, while  cf.logCustomData()  writes to CloudFront access logs. You can use both methods in the same function.

4. Prerequisites

  • An available CloudFront distribution.
  • A CloudFront Function that uses JavaScript runtime 2.0. The  cf.logCustomData()  method depends on the  cloudfront  module.
  • Standard logging (v2) or real-time logs enabled, with permission to modify the field configuration.
  • If you want to run the Athena examples in this article, standard logging (v2) must deliver logs to Amazon S3.

5. Configuration

5.1 Write a CloudFront Function

Import the  cloudfront  module in a JavaScript runtime 2.0 function:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;

// Record the value of the debug request header when it is present.
if (request.headers['x-debug-header']) {
cf.logCustomData("debug header found: " + request.headers['x-debug-header'].value);
}

return request;
}
When recording structured data, convert it to a string with  JSON.stringify()  first:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;

var logObj = {
path: request.uri,
hasAuth: !!request.headers['authorization']
};

// logCustomData accepts a single string argument.
cf.logCustomData(JSON.stringify(logObj));

return request;
}

5.2 Enable the Log Fields in Standard Logging (v2)

If the log configuration does not select the corresponding field, the value from  cf.logCustomData()  does not appear in the delivered logs. Configure standard logging (v2) as follows:
  1. Open the CloudFront console and select the target distribution;
  1. Open Logging, then create or edit the standard logging (v2) access log destination;
  1. Add  viewer-request-log-data  under Field selection. If you use a Viewer Response function, also add  viewer-response-log-data ;
  1. Save the configuration and confirm that logging is Enabled.
Standard logging (v2) can deliver logs to Amazon CloudWatch Logs, Amazon Data Firehose, or Amazon S3. The query examples later in this article use Amazon S3 and Amazon Athena.

5.3 Enable the Log Fields in Real-Time Logs

For real-time logs delivered to Amazon Kinesis Data Streams, add the same fields to the real-time log configuration:
  •  viewer-request-log-data 
  •  viewer-response-log-data 

5.4 Associate the Function with the Distribution

In the relevant cache behavior of the CloudFront distribution, associate the function with the Viewer Request or Viewer Response event. Then publish the function and wait for the distribution deployment to complete.

6. Examples

6.1 Extract Values from Cookies and Query Strings

Cookies and query strings generally appear as complete fields in access logs. A function can extract selected values such as an anonymous session ID,  utm_source , or  gclid , and write them to a custom log field.
The CloudFront Functions event object parses cookies into  request.cookies , so you do not need to parse the  Cookie  header yourself. The following function records one anonymous session cookie:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;

if (request.cookies.session_id) {
cf.logCustomData(JSON.stringify({
session_id: request.cookies.session_id.value
}));
}

return request;
}
Query strings are available in  request.querystring . The following function extracts two parameters and uses an empty string when one is not present:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;
var query = request.querystring;

if (query.utm_source || query.gclid) {
var attribution = {
src: query.utm_source ? query.utm_source.value : '',
gclid: query.gclid ? query.gclid.value : ''
};
cf.logCustomData(JSON.stringify(attribution));
}

return request;
}
> If you need to preserve the original parameter order or encoding, use  request.rawQueryString()  in runtime 2.0. When you only need selected parameters, read them directly from  request.querystring .
After the data is delivered to Amazon S3, you can use Athena to aggregate it by session or campaign. Real-time logs can be processed by consumers of Amazon Kinesis Data Streams. Custom fields are URL-encoded before delivery, so decode them before querying.

6.2 A/B Test Assignments

The following function reads an existing experiment cookie and writes the assignment to the access log. The experiment design is responsible for assigning and setting the cookie:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;

var experimentCookie = request.cookies.homepage_experiment;
var bucket = experimentCookie ? experimentCookie.value : 'unassigned';

cf.logCustomData(JSON.stringify({
exp: 'homepage-hero-2026q3',
variant: bucket
}));

return request;
}
You can use  variant  in access log queries to compare status code distributions and cache hit rates across groups.

6.3 Authorization Input State

The following function records whether the request includes an Authorization header. If the function performs actual validation, record only categories such as  allow ,  deny , or  expired ; do not write credentials or tokens to the log:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;
var outcome = request.headers['authorization'] ? 'present' : 'missing';

cf.logCustomData(JSON.stringify({ auth: outcome }));

return request;
}
> This example only demonstrates log delivery and is not a complete authorization implementation. Do not record complete Authorization headers, cookies, JWTs, or other credentials.

6.4 Routing Decisions

Record which URL rewrite strategy the function used:
import cf from 'cloudfront';

function handler(event) {
var request = event.request;

var rewrite = 'unchanged';
if (request.uri.startsWith('/legacy/')) {
request.uri = '/v2/' + request.uri.slice('/legacy/'.length);
rewrite = 'legacy-to-v2';
}

cf.logCustomData(JSON.stringify({ rewrite: rewrite }));

return request;
}

6.5 Other Data You Can Record

Data calculated by a function that does not have a corresponding access log field can also be written to a custom log field. For example:
Scenario
Example data
Use
Geographic or edge location labels
 cf.edgeLocation.name  (IATA code),  .region , or a derived business market label such as  market=EMEA 
Add business geography to the native  c-country  field (Viewer Request only)
Bot classification
 bot=true;cat=scraper;score=87 
Record a classification that is not present in the raw User-Agent
Cache key or personalization dimensions
 dev=mobile;cur=USD;lang=en 
Explain cache hit and miss patterns
Request correlation or trace ID
A generated or propagated business trace ID or  traceparent 
Correlate CDN logs with backend or OpenTelemetry traces
Response-side enrichment
 personalized=true , a content version, or similar data recorded by a Viewer Response function
Write to  viewer-response-log-data  alongside request-side data
> Viewer Request and Viewer Response functions write to different fields ( viewer-request-log-data  and  viewer-response-log-data ). A single access log record can therefore contain both request-side decisions and response-side results.

7. Analyze Logs with Amazon Athena

After standard logging (v2) delivers logs to Amazon S3, you can query them with Athena. Custom log fields are URL-encoded strings. Queries generally need  url_decode ; if the decoded value is JSON, you can then use  json_extract  or  json_extract_scalar .
The following query counts requests by experiment group and calculates the error rate. Column names must match the Athena table definition in your environment:
-- Count requests and the 4xx/5xx rate for each A/B test group.
WITH decoded_logs AS (
SELECT
json_extract_scalar(
url_decode("viewer-request-log-data"),
'$.variant'
) AS variant,
"sc-status"
FROM cloudfront_standard_logs
WHERE "viewer-request-log-data" NOT IN ('', '-')
)
SELECT
variant,
COUNT(*) AS requests,
SUM(CASE WHEN CAST("sc-status" AS INTEGER) \>= 400 THEN 1 ELSE 0 END) * 1.0
/ COUNT(*) AS error_rate
FROM decoded_logs
WHERE variant IS NOT NULL
GROUP BY 1
ORDER BY requests DESC;
If you record  session_id  as in section 6.1, you can extract it from the decoded JSON:
-- Count requests by anonymous session ID and find the most active sessions.
WITH decoded_logs AS (
SELECT
json_extract_scalar(
url_decode("viewer-request-log-data"),
'$.session_id'
) AS session_id,
"sc-bytes"
FROM cloudfront_standard_logs
WHERE "viewer-request-log-data" NOT IN ('', '-')
)
SELECT
session_id,
COUNT(*) AS requests,
SUM(CAST("sc-bytes" AS BIGINT)) AS total_bytes
FROM decoded_logs
WHERE session_id IS NOT NULL
GROUP BY 1
ORDER BY requests DESC
LIMIT 100;
Because  variant ,  session_id ,  sc-status , and  sc-bytes  are in the same record, these queries do not need to join Amazon CloudWatch Logs.

8. Costs and Log Selection

Calling  cf.logCustomData()  does not incur an additional fee. CloudFront Functions invocations and access log delivery are billed under their standard pricing. Real-time logs also involve charges for CloudFront real-time logs and Amazon Kinesis Data Streams.
Total cost depends on the log type, sampling rate, number of fields, delivery destination, retention period, and query method. Choose the log path based on the use case:
Requirement
Recommendation
CloudFront Function development, testing, and troubleshooting
Use  console.log()  with Amazon CloudWatch Logs
Analyze function decisions together with request results in one record
Use  cf.logCustomData()  with CloudFront access logs
Batch analysis and long-term retention
Deliver standard logging (v2) to Amazon S3 and use Athena as needed
Second-level consumption and response workflows
Deliver real-time logs to Amazon Kinesis Data Streams and set an appropriate sampling rate
Limit log content to the fields you need, and configure retention or lifecycle policies for the delivery destination. Prices vary by Region and usage. Before deployment, estimate costs with the AWS Pricing Calculator or the pricing page for the relevant service.

9. Limits and Considerations

Item
Limit or recommendation
Parameter type
Accepts a single string. Call  JSON.stringify()  before passing an object.
Field size
Each field can contain up to 800 bytes.
Encoding
CloudFront automatically URL-encodes the value before delivery.
Size limit
Values exceeding 800 bytes after URL encoding are truncated. Record only the fields you need and avoid large objects.
Multiple calls
When called multiple times during one execution, only the last value is retained. Combine multiple values into one JSON string and write it once.
Event phase
Supports Viewer Request ( viewer-request-log-data ) and Viewer Response ( viewer-response-log-data ).
Unsupported locations
Embedded POPs do not support custom data logging.
Runtime
Requires JavaScript runtime 2.0.
With  console.log() 
The methods serve different purposes and can coexist:  console.log()  writes to Amazon CloudWatch Logs for debugging, while  cf.logCustomData()  writes to CloudFront access logs for analysis.
No value
If no function is associated or the function does not call the method, the corresponding log field contains  - .
Privacy
Do not record passwords, complete tokens, personally identifiable information (PII), or other sensitive data. Set access controls and retention periods according to your organization's policies.

10. Summary

 cf.logCustomData()  records function data alongside CloudFront request results. Keep debugging output in  console.log()  and use access log custom fields for analysis data such as A/B assignments, authorization outcomes, and URL rewrite results.
Start with one field in a test distribution. Confirm the log configuration, URL decoding, and downstream queries before adding more fields.
References
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article