Skip to content

Commit

Permalink
Added better success / fail handling for contact form
Browse files Browse the repository at this point in the history
  • Loading branch information
BenjaminEHowe committed Jul 13, 2024
1 parent 678bdce commit 9e7537f
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 4 deletions.
10 changes: 10 additions & 0 deletions 11ty-src/contact-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
layout: default.njk
title: Contact - failure
---

# {{ title }}

Something went wrong, and your message was not sent.
Please try again.
[Go home](/).
9 changes: 9 additions & 0 deletions 11ty-src/contact-success.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
layout: default.njk
title: Contact - success
---

# {{ title }}

Your message was successfully sent.
[Go home](/).
1 change: 0 additions & 1 deletion eleventy.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export default async function (eleventyConfig) {
if ((this.page.outputPath || "").endsWith(".html")) {
let minified = htmlmin.minify(content, {
collapseBooleanAttributes: true,
collapseInlineTagWhitespace: true,
collapseWhitespace: true,
decodeEntities: true,
minifyCSS: true,
Expand Down
7 changes: 4 additions & 3 deletions functions/api/contact.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,22 @@ export async function onRequest(context) {
const fields = Object.fromEntries(formData.entries());
fields.cf = context.request.cf;
fields.headers = Object.fromEntries(context.request.headers.entries());
const url = new URL(context.request.url);
if (fields[HONEYPOT_FIELD] === "") {
delete fields[HONEYPOT_FIELD];
const sent = await sendFormViaResend({
apiKey: context.env.RESEND_KEY,
emailFrom: context.env.EMAIL_FROM,
emailTo: context.env.EMAIL_TO,
fields,
subject: `Form submission from ${new URL(context.request.url).hostname}`,
subject: `Form submission from ${url.hostname}`,
});

if (!sent) {
return new Response("Oops! Something went wrong. Please try submitting the form again.", { status: 500 });
return Response.redirect(`https://${url.hostname}/contact-fail`, 303);
}
}
return Response.redirect(context.request.headers.get("Referer"), 303);
return Response.redirect(`https://${url.hostname}/contact-success`, 303);
}

async function sendFormViaResend({
Expand Down

0 comments on commit 9e7537f

Please sign in to comment.