I have a simple contact form in a NextJS app and I wanted to switch from emailjs to something custom.
The contact form works perfect in development, but in production(cpanel, not vercel) I get a status 500 error(Internal Server Error). I've researched around and implemented async/await, promises, res.send status and everything I've found but I still can't find a way through.
Here's the post method:
const checkForm = async () => {
try {
const values = await form.validateFields();
fetch('/api/contact', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
});
} catch (error) {
console.log('Failed:', error);
}
};
And the /api/contact
import nodemailer from 'nodemailer';
export default async (req, res) => {
const { first_name, last_name, email, phone_number, subject, message } = req.body;
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
await new Promise((resolve, reject) => {
transporter.verify(function (error, success) {
if (error) {
console.log(error);
reject(error);
} else {
console.log('Server is ready to take our messages');
resolve(success);
}
});
});
const mailOption = {
from: `${email}`,
replyTo: `${email}`,
to: `${process.env.EMAIL}`,
subject: `${subject}`,
html: `<p><strong>Name:</strong> ${first_name + ' ' + last_name}</p>
<p><strong>Email:</strong> <a href="mailto:${email}">${email}</a></p>
<p><strong>Phone number:</strong> ${phone_number}</p>
<p><strong>Message:</strong><br /> ${message}</p>
`
};
await new Promise((resolve, reject) => {
transporter.sendMail(mailOption, (err, info) => {
if (err) {
console.error(err);
reject(err);
res.send('error:' + JSON.stringify(err));
} else {
console.log(info);
resolve(info);
res.send('success');
}
});
});
res.status(200).json({ status: 'OK' });
};