mise a jour du frontend

This commit is contained in:
toine 2025-10-05 08:52:12 +02:00
parent 618b740588
commit 9737caff99
9 changed files with 332 additions and 60 deletions

View file

@ -24,3 +24,92 @@ export async function GET() {
return NextResponse.json({ error: "Unexpected error" }, { status: 500 });
}
}
export async function POST(req: Request) {
try {
const RESEND_API_KEY = process.env.RESEND_API_KEY;
const RESEND_FROM = process.env.RESEND_FROM || "no-reply@resend.dev";
const CONTACT_TO = process.env.CONTACT_TO || process.env.CONTACT_EMAIL; // fallback name
if (!RESEND_API_KEY) {
return NextResponse.json({ error: "RESEND_API_KEY not configured" }, { status: 500 });
}
if (!CONTACT_TO) {
return NextResponse.json({ error: "CONTACT_TO (destination email) not configured" }, { status: 500 });
}
const payload = await req.json().catch(() => null);
if (!payload || typeof payload !== "object") {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const name = String(payload.name || "").trim();
const email = String(payload.email || "").trim();
const subject = String(payload.subject || "").trim() || "Nouveau message via le site";
const message = String(payload.message || "").trim();
if (!name || !email || !message) {
return NextResponse.json({ error: "Champs requis manquants: name, email, message" }, { status: 400 });
}
// Basic email format check (very permissive)
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return NextResponse.json({ error: "Email invalide" }, { status: 400 });
}
const html = `
<div>
<p><strong>Nom:</strong> ${escapeHtml(name)}</p>
<p><strong>Email:</strong> ${escapeHtml(email)}</p>
<p><strong>Sujet:</strong> ${escapeHtml(subject)}</p>
<p><strong>Message:</strong><br/>${escapeHtml(message).replace(/\n/g, '<br/>')}</p>
</div>
`;
const resendRes = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
"Authorization": `Bearer ${RESEND_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: RESEND_FROM,
to: [CONTACT_TO],
reply_to: [email],
subject: subject,
html,
text: `Nom: ${name}\nEmail: ${email}\nSujet: ${subject}\n\n${message}`,
}),
});
const text = await resendRes.text();
if (!resendRes.ok) {
try {
const err = JSON.parse(text);
return NextResponse.json(err, { status: resendRes.status });
} catch {
return new NextResponse(text || "Failed to send message via Resend", { status: resendRes.status });
}
}
try {
const json = JSON.parse(text || "{}");
return NextResponse.json(json, { status: 200 });
} catch {
return NextResponse.json({ ok: true }, { status: 200 });
}
} catch (error) {
return NextResponse.json({ error: "Unexpected error" }, { status: 500 });
}
}
// Small helper to prevent HTML injection in email body
function escapeHtml(input: string): string {
return input
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}