export default {
async fetch(request, env) {
// After launch, replace * with your real domain:
// const ALLOWED_ORIGIN = 'https://aestheticleadersdinner.com';
const ALLOWED_ORIGIN = 'https://aestheticleadersdinner.com';
// Handle CORS preflight
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
});
}
// Only accept POST to /api/chat
const url = new URL(request.url);
if (request.method !== 'POST' || url.pathname !== '/api/chat') {
return new Response('Not found.', { status: 404 });
}
// Parse request body
let body;
try {
body = await request.json();
} catch {
return new Response('Bad request.', { status: 400 });
}
const { messages, system } = body;
if (!messages || !Array.isArray(messages)) {
return new Response('Invalid payload.', { status: 400 });
}
// Forward to Anthropic — API key stays server-side
const anthropicRes = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': env.ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({
model: 'claude-sonnet-4-20250514',
max_tokens: 1000,
system: system || '',
messages: messages,
}),
});
const data = await anthropicRes.json();
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
},
});
}
};