diff --git a/.env.example b/.env.example index 2aaf9f9..e6e9553 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,10 @@ RESEND_API_KEY=re_your_api_key_here # Email address that receives contact form submissions RESEND_TO=vbvwithnate@outlook.com +# Optional: automatically add contact form submitters to a Resend Segment +# Create a Segment in Resend and paste its ID here if you want new contacts grouped. +RESEND_SEGMENT_ID= + # "From" address shown on received emails. # During testing you can leave this as-is (uses Resend's shared domain). # For production: verify your own domain at resend.com/domains and change this. diff --git a/server.js b/server.js index c7d8447..ee7e2b1 100644 --- a/server.js +++ b/server.js @@ -13,6 +13,14 @@ function escapeHtml(value) { .replace(/'/g, ''') } +function splitName(fullName) { + const parts = fullName.trim().split(/\s+/).filter(Boolean) + return { + firstName: parts[0] ?? '', + lastName: parts.slice(1).join(' '), + } +} + const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) const DATA_DIR = path.join(__dirname, 'data') @@ -113,6 +121,43 @@ app.post('/api/contact', contactRateLimit, async (req, res) => { }) const resend = new Resend(process.env.RESEND_API_KEY) + const { firstName, lastName } = splitName(trimmedName) + + try { + const { error: contactError } = await resend.contacts.create({ + email: trimmedEmail, + firstName, + lastName, + unsubscribed: false, + ...(process.env.RESEND_SEGMENT_ID + ? { segments: [{ id: process.env.RESEND_SEGMENT_ID }] } + : {}), + properties: { + source: 'website-contact-form', + last_message_at: new Date().toISOString(), + }, + }) + + if (contactError) { + const { error: updateError } = await resend.contacts.update({ + email: trimmedEmail, + firstName, + lastName, + unsubscribed: false, + properties: { + source: 'website-contact-form', + last_message_at: new Date().toISOString(), + }, + }) + + if (updateError) { + console.error('[contact] contact sync error:', updateError) + } + } + } catch (contactSyncErr) { + console.error('[contact] contact sync exception:', contactSyncErr) + } + const { error } = await resend.emails.send({ from: process.env.RESEND_FROM ?? 'Verse by Verse with Nate ', to: [process.env.RESEND_TO ?? 'vbvwithnate@outlook.com'],