hono icon indicating copy to clipboard operation
hono copied to clipboard

try catch cloudfront event -> request mapping for lambda@edge handler to avoid undefined access errors

Open dwm-mcollins opened this issue 3 months ago • 3 comments

What is the feature you are proposing?

As is, this mapper assumes the event is well formed and valid.

When testing the lambda@edge via the aws console using the prefilled example json, which is just an array of foobar type dummy ids, the handler throws with "cannot access undefined when reading "0" as it tries to index into an array that doesnt exist.

Ideally it should try catch and return an error message along the lines of "Unable to map cloudfront request to request object when handling request: malformed cloudfront edge event"

problematic code:

const createRequest = (event: CloudFrontEdgeEvent): Request => {
  const queryString = event.Records[0].cf.request.querystring
  const host =
    event.Records[0].cf.request.headers?.host?.[0]?.value ||
    event.Records[0].cf.config.distributionDomainName
  const urlPath = `https://${host}${event.Records[0].cf.request.uri}`
  const url = queryString ? `${urlPath}?${queryString}` : urlPath

  const headers = new Headers()
  Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => {
    v.forEach((header) => headers.set(k, header.value))
  })

  const requestBody = event.Records[0].cf.request.body
  const method = event.Records[0].cf.request.method
  const body = createBody(method, requestBody)

  return new Request(url, {
    headers,
    method,
    body,
  })
}

dwm-mcollins avatar Sep 19 '25 00:09 dwm-mcollins

Im happy to make a PR for this, however im unsure if there were good reasons this try catch was not performed.

dwm-mcollins avatar Sep 19 '25 00:09 dwm-mcollins

@dwm-mcollins Thank you for proposing.

Hey @watany-dev Do you have any thoughts about this?

yusukebe avatar Sep 22 '25 06:09 yusukebe

@dwm-mcollins I'm not very familiar with the sample data provided in the console, but does the dummy schema meet the event specifications assumed by L@E? https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html

watany-dev avatar Sep 25 '25 14:09 watany-dev