mon-site-perso/frontend/app/api/contact/route.ts
2025-10-05 08:52:12 +02:00

115 lines
3.7 KiB
TypeScript

import { NextResponse } from "next/server";
export async function GET() {
try {
const baseUrl = process.env.BACKEND_URL;
if (!baseUrl) {
return NextResponse.json({ error: "BACKEND_URL not configured" }, { status: 500 });
}
const url = `${baseUrl.replace(/\/$/, "")}/contact`;
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) {
return NextResponse.json({ error: "Failed to fetch contact data" }, { status: res.status });
}
const data = await res.json();
// Ensure we only expose expected fields
const { email, linkedin, github } = data || {};
return NextResponse.json({ email, linkedin, github }, { status: 200 });
} catch (error) {
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;');
}