iTranslated by AI
Supporting POST/PUT Requests with CloudFront + Lambda Function URLs + Hono + htmx
Currently, it seems that the best way to use Lambda Function URLs safely is to combine them with CloudFront's OAC.
However, while there are no issues with GET requests alone, there is a problem where POST/PUT requests that do not have the payload's hash value in the header are not allowed.
Note
If you use PUT or POST methods with your Lambda function URL, your users must include the payload hash value in the x-amz-content-sha256 header when sending the request to CloudFront. Lambda doesn't support unsigned payloads.
Using POST/PUT Requests with Lambda Function URLs
When making a POST request with cURL, it can be resolved by calculating the hash value of the payload and adding the x-amz-content-sha256 header (Reference).
curl -X POST https://<distribution-id>.cloudfront.net/post \
-H "x-amz-content-sha256:$(echo -n '{"name": "John Doe", "age": 32}' | openssl dgst -sha256 -hex | cut -d' ' -f2)" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "age": 32}'
When creating a simple web application with Hono + htmx, I struggled with adding the payload hash value to the header, so I will write about how I resolved it.
Preparing the Base Application
I am assuming a state where the project has already been created using the AWS CDK. To make it easier to explain, let's consider an app that searches for movies as an example.
First, ensure that when / is accessed, HTML that allows searching is returned. The search functionality will use htmx.
// index.tsx
const app = new Hono();
app.get("/", (c) => {
return c.render(
<main>
<h1>Movie Search</h1>
<input
id="search"
type="text"
name="q"
hx-post="/search"
hx-trigger="keyup delay:500ms changed"
hx-target="#result"
/>
<div id="result"/>
</main>
);
});
export const handler = handle(app);
Create a layout using the jsxRenderer middleware. The CDN version of htmx is loaded here.
// index.tsx
app.use(jsxRenderer(({ children }) => <Layout>{children}</Layout>));
// ./Layout.tsx
import { html } from "hono/html";
import type { FC } from "hono/jsx";
export const Layout: FC = ({ children }) => html`
<!doctype html>
<html lang="ja">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/htmx.org@2.0.3" integrity="sha384-0895/pl2MU10Hqc6jd4RvrthNlDiE9U1tWmX7WRESftEDRosgxNsQG/Ze9YMRzHq" crossorigin="anonymous"></script>
<title>Movie Search</title>
</head>
<body>
${props.children}
</body>
</html>
`;
Back in index.tsx, add POST /search for the search functionality.
// index.tsx
app.post('/search', async (c) => {
const q = (await c.req.formData()).get('q');
if (typeof q !== 'string' || q === '') return c.text('');
const items = await searchMovie(q);
return c.html(
items.length > 0 ? (
<MovieList items={items}/>
) : (
<p>該当するものが見つかりませんでした</p>
)
);
});
Checking the Operation
Update Lambda and check the behavior.
% cdk deploy --hotswap

{"message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}
As mentioned earlier, a 403 error is returned.
Modifying the Request to Succeed
Add the following script to Layout.tsx.
<script>
let hashValue = null;
const calcHash = (event, data) => {
if (hashValue === null) {
event.preventDefault();
crypto.subtle.digest("SHA-256", new TextEncoder().encode(data)).then(hashBuffer => {
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hash = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
hashValue = hash;
event.detail.issueRequest();
});
}
}
htmx.on("htmx:configRequest", (event) => {
if (hashValue) {
event.detail.headers["x-amz-content-sha256"] = hashValue;
}
});
htmx.on("htmx:afterRequest", () => {
hashValue = null;
});
</script>
The calcHash function will be explained later as it is used in index.tsx.
htmx:configRequest is an event called before a request is issued, so we rewrite the header here. Since htmx:afterRequest is called after the request, we reset hashValue. Although there is only one input this time, we define htmx:configRequest and htmx:afterRequest globally so they can be treated as common processes.
Calculating the Hash Value and Issuing the Request
To perform the hash calculation when the user confirms text input in the search field of index.tsx, add the hx-on--confirm attribute and call the calcHash function. This function asynchronously calculates the hash value and stores the result in hashValue.
<input
id="search"
type="text"
name="q"
hx-post="/search"
hx-trigger="keyup delay:500ms changed"
hx-target="#result"
+ hx-on--confirm="calcHash(event, 'q=' + event.detail.elt.value)"
/>
Here, the second argument passed to the calcHash function is a string constructed for the request payload. In this example, since the search query is passed as a parameter, it is specified in the format q=[search string]. Also, in the case of content-type: application/json, you would pass a JSON string.
Asynchronous Request Issuance
In the calcHash function, hash calculation is performed asynchronously through the following steps:
- Call
event.preventDefault()on thehtmx:confirmevent to prevent the request from being issued immediately. - Calculate the hash value of the data using
crypto.subtle.digest(), and store it inhashValueonce the calculation is complete. - Call
event.detail.issueRequest()to issue the request when everything is ready.
By utilizing this asynchronous process, you can ensure that the hash value is calculated right before the request is sent and then added to the header.
Why Separate the Request and Hash Calculation?
Since asynchronous processing is not possible within the htmx:configRequest event, the hash value must be calculated synchronously before the request. By performing the asynchronous processing inside the htmx:confirm event and then manually issuing the request after completion, we can bypass this limitation.
Redeploy and Re-run
After redeploying and testing the search, I confirmed that the header was correctly attached and verified the response.

Summary and Impressions
- I confirmed that POST/PUT requests can be used with CloudFront + Lambda Function URLs. This is a stack I find extremely useful for building small tools, so I'm very happy that I can now use it in professional projects by adding WAF.
- Storing the payload's hash value in the header is the key point. I provided an example of how to handle this when using Hono + htmx.
- It is somewhat difficult to develop because the JavaScript within htmx events becomes a string.
- It's not very elegant that the variable for storing the hash value and the calculation function end up in the global scope.
References
Discussion