app/api/invite/route.js:
import sgMail from '@sendgrid/mail'
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
export async function POST(req) {
const { email } = await req.json()
if (!email || !email.includes('@')) {
return Response.json({ error: 'valid email required' }, { status: 400 })
}
try {
await sgMail.send({
to: email,
from: '[YOUR_VERIFIED_SENDER]', // verified sender
subject: 'Your invite',
text: 'Welcome aboard',
})
return Response.json({ sent: true }, { status: 202 })
} catch (error) {
const body = error.response && error.response.body
console.error(body)
return Response.json({ sent: false, detail: body }, { status: 502 })
}
}
Rules:
1. The key lives in server env only. Never import this module or the key into a client component.
2. Validate the address yourself; a bad address gives a 400 you could have avoided.
3. Rate-limit the route or add a captcha if it is public; an open mail endpoint gets abused fast.