// Copy to app/api/email-example/route.ts in a local Next.js App Router project. // Run email-mock-server.mjs separately. This route is development-only. // It always calls the local fixture. It cannot send real email. export async function POST(request: Request) { if (process.env.NODE_ENV !== 'development') return new Response(null, { status: 404 }); const url = new URL(request.url); if (!['localhost', '127.0.0.1'].includes(url.hostname) || request.headers.get('origin') !== url.origin) { return Response.json({ error: 'Local same-origin requests only' }, { status: 403 }); } const key = request.headers.get('idempotency-key'); if (!key || !/^[a-zA-Z0-9:_-]{1,120}$/.test(key)) { return Response.json({ error: 'Supply a stable Idempotency-Key' }, { status: 400 }); } try { const response = await fetch('http://127.0.0.1:3027/api/v1/emails', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key }, body: JSON.stringify({ from: 'hello@example.test', to: 'reader@example.test', subject: 'A local test', text: 'No email leaves this fixture.' }), signal: AbortSignal.timeout(5000), cache: 'no-store', }); const result = await response.json(); if (!response.ok) return Response.json({ error: 'Fixture rejected the request' }, { status: response.status }); return Response.json(result, { status: 202 }); } catch { return Response.json({ error: 'Result unknown. Retry with the same key.' }, { status: 503 }); } }