diff --git a/src/app/(marketing)/contact/actions.ts b/src/app/(marketing)/contact/actions.ts index 70153aa..24403b4 100644 --- a/src/app/(marketing)/contact/actions.ts +++ b/src/app/(marketing)/contact/actions.ts @@ -3,9 +3,21 @@ import { Resend } from 'resend'; import { z } from 'zod'; -const resend = new Resend(process.env.RESEND_API_KEY); const companyEmail = process.env.COMPANY_EMAIL || 'contact@novalon.cn'; +let resend: Resend | null = null; + +function getResend(): Resend { + if (!resend) { + const apiKey = process.env.RESEND_API_KEY; + if (!apiKey) { + throw new Error('RESEND_API_KEY environment variable is not set'); + } + resend = new Resend(apiKey); + } + return resend; +} + const contactFormSchema = z.object({ name: z.string().min(2, '姓名至少需要2个字符'), phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号码'), @@ -244,7 +256,7 @@ export async function submitContactForm( `; try { - const { data: emailData, error } = await resend.emails.send({ + const { data: emailData, error } = await getResend().emails.send({ from: '睿新致远官网 ', to: [companyEmail], subject: `📧 ${data.subject} - ${data.name}`, diff --git a/src/app/api/contact/route.ts b/src/app/api/contact/route.ts index 50489db..ef62a97 100644 --- a/src/app/api/contact/route.ts +++ b/src/app/api/contact/route.ts @@ -3,9 +3,21 @@ import { Resend } from 'resend'; import { z } from 'zod'; import { SecurityMiddleware } from '@/lib/security/middleware'; -const resend = new Resend(process.env.RESEND_API_KEY); const companyEmail = process.env.COMPANY_EMAIL || 'contact@novalon.cn'; +let resend: Resend | null = null; + +function getResend(): Resend { + if (!resend) { + const apiKey = process.env.RESEND_API_KEY; + if (!apiKey) { + throw new Error('RESEND_API_KEY environment variable is not set'); + } + resend = new Resend(apiKey); + } + return resend; +} + let securityMiddleware = new SecurityMiddleware(); export function setSecurityMiddleware(middleware: SecurityMiddleware) { @@ -108,7 +120,7 @@ export async function POST(request: NextRequest) { `; - const result = await resend.emails.send({ + const result = await getResend().emails.send({ from: '睿新致远官网 ', to: [companyEmail], subject: `${sanitizedData.subject} - ${sanitizedData.name}`,