Skip to content

Commit

Permalink
Merge pull request #65 from celestiaorg/hotfix/added-cors-to-newsletter
Browse files Browse the repository at this point in the history
Hotfix/added cors to newsletter
  • Loading branch information
sysrex authored Jan 28, 2025
2 parents fbc9b04 + abfa23c commit 4609bd2
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/components/Newsletter/Newsletter.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,29 @@ const Newsletter = () => {
try {
setIsSubmitting(true);

console.log("Sending request with:", { email, recaptchaToken: token });
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

const response = await fetch("https://eff999e9-celestia-newsletter-worker.infra-admin-749.workers.dev/", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
email,
recaptchaToken: token,
}),
body: JSON.stringify({ email }),
mode: "cors",
signal: controller.signal,
});

console.log("Response status:", response.status);
clearTimeout(timeoutId);

const data = await response.json();
console.log("Response data:", data);

if (response.status === 429) {
setStatus("Error");
setMsg("Too many requests. Please try again later.");
return;
}

if (data.success) {
setStatus("Success");
Expand All @@ -82,7 +87,9 @@ const Newsletter = () => {
}
} catch (error) {
setStatus("Error");
setMsg("An unexpected error occurred. Please try again.");
const errorMessage =
error.name === "AbortError" ? "Request timed out. Please try again." : "Unable to subscribe at this time. Please try again later.";
setMsg(errorMessage);
} finally {
setIsSubmitting(false);
reCaptchaRef.current?.reset();
Expand Down
73 changes: 73 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
export default {
async fetch(request, env) {
const corsHeaders = {
"Access-Control-Allow-Origin": "*", // Consider changing to your domain
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "86400",
};

// Handle OPTIONS
if (request.method === "OPTIONS") {
return new Response(null, {
headers: corsHeaders,
});
}

// Handle POST
if (request.method === "POST") {
const headers = {
...corsHeaders,
"Content-Type": "application/json",
};

try {
const { email } = await request.json();

if (!email) {
return new Response(JSON.stringify({ error: "Email required" }), {
status: 400,
headers,
});
}

// Call Mailchimp API
const DATACENTER = env.MAILCHIMP_API_KEY.split("-")[1];
const response = await fetch(`https://${DATACENTER}.api.mailchimp.com/3.0/lists/${env.MAILCHIMP_LIST_ID}/members`, {
method: "POST",
headers: {
Authorization: `Bearer ${env.MAILCHIMP_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
email_address: email,
status: "subscribed",
}),
});

const mailchimpData = await response.json();

if (response.status === 200 || response.status === 201) {
return new Response(JSON.stringify({ success: true }), { headers });
}

if (mailchimpData.title === "Member Exists") {
return new Response(JSON.stringify({ error: "Already subscribed" }), { headers });
}

throw new Error(mailchimpData.detail || "Mailchimp error");
} catch (err) {
return new Response(JSON.stringify({ error: err.message }), {
status: 500,
headers,
});
}
}

// Handle unsupported methods
return new Response("Method not allowed", {
status: 405,
headers: corsHeaders,
});
},
};

0 comments on commit 4609bd2

Please sign in to comment.