1. npm install @sendgrid/mail. Initialize once at startup, not per request:
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
2. Send inside the handler and surface real errors:
app.post('/invite', async (req, res) => {
const msg = {
to: req.body.email,
from: '[YOUR_VERIFIED_SENDER]', // verified sender
subject: 'Your invite',
text: 'Welcome aboard',
}
try {
await sgMail.send(msg)
res.status(202).json({ sent: true })
} catch (error) {
console.error(error.response && error.response.body)
res.status(502).json({ sent: false, detail: error.response && error.response.body })
}
})
3. Validate req.body.email before sending; a malformed address gives you a 400 with a field-level error, which is cheaper to catch yourself.
4. Never expose SENDGRID_API_KEY to the browser bundle. If the frontend needs to trigger mail, it calls this route; the key stays server-side.