I'm trying to follow this tutorial to put an email capture form in a NextJS site: https://betterprogramming.pub/how-to-create-a-working-contact-form-in-next-js-459d1fc992ea
Because it's not a full contact form, I dropped all of the fields except the email.
My api/contact.js looks like this:
const mail = require('@sendgrid/mail');
mail.setApiKey(process.env.SENDGRID_API_KEY);
export default async (req, res) => {
const body = JSON.parse(req.body);
const message = `
Email: ${body.email}
`;
const data = {
to: 'SENDER-EMAIL',
from: 'RECEIVER-EMAIL',
subject: `New message from ${body.email}`,
text: message,
html: message.replace(/\r\n/g, '<br />'),
};
await mail.send(data);
res.status(200).json({ status: 'OK' });
};
And inside index.js, the form looks like this:
<form onSubmit={handleSubmit} className={styles.form}>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Send</button>
</form>
The form displays properly on the site, but I get a 500 error when I try submit an email in production. I also tried on localhost and got an error.
I npm installed the sendgrid package. I also have my secret in a .env.local.
I'm not sure what's going on.
It sounds like you are getting an error when you call on await mail.send(data). There could be a couple of reasons for this, but first we should see how to find out what the error is.
We need to wrap the call to send the email in a try/catch block. That way we can handle the error and inspect it to see what is wrong. We can also control the response to your front-end instead of dealing with the default 500 handler.
At the bottom of your api/contact.js function update to:
try {
await mail.send(data);
res.status(200).json({ status: 'OK' });
} catch (error) {
console.log(error);
if (error.response) {
console.log(error.response.body);
}
res.status(400).json({ status: "ERROR", message: error.message });
}
Now when there is an error we log the error to the server logs and return a message to the front-end. Note, that message may not be suitable for users and you might want to detect errors and return a better message yourself.
Now you are logging the error you should be able to see what it says. And it should direct you to what I think is one of these issues:
Your API key is wrong
Either, you have set it incorrectly, or you added it to your .env.local correctly and need to fully restart your server
Your API key doesn't have permission to send emails
When you create an API key, you can choose to give it all permissions or just a subset. Make sure your API key has the permission to send emails.
Your trying to send from an email address that SendGrid doesn't know you own
To send emails from an email address using SendGrid, you either need to verify the email address is yours or authenticate that the domain is yours (domain authentication is recommended for production applications)