I'm having a problem with the headers of my post API endpoint created in Nextjs.
My endpoint is for form submission and I forward the input to my email. My current code can send the email and I receive it fine in my email, but every time I make a request it returns an error in the header.
import { NextResponse, NextRequest } from "next/server" import nodemailer from "nodemailer" export async function POST(request: NextRequest, response: NextResponse) { const formData = await request.formData() const emailValue = formData.get("email") const messageValue = formData.get("message") const numberValue = formData.get("phone_number") if (!messageValue || !numberValue || !emailValue) { return NextResponse.json({ message: "Please fill in all required fields!" }, { status: 400 }) } const transporter = nodemailer.createTransport({ service: "gmail", auth: { user: process.env.EMAIL, pass: process.env.PASSWORD, }, tls: { rejectUnauthorized: false, }, }) const mailOptions = { from: `${emailValue}`, to: `${process.env.EMAIL}`, subject: `Message from contact me page ${numberValue} - ${emailValue} `, text: `${messageValue}`, } transporter.sendMail(mailOptions, (err, info) => { if (err) { return NextResponse.json({ message: `${err}` }, { status: 500 }) } return NextResponse.json({ message: "Email sent successfully!" }, { status: 200 }) }) }
I'm not sure what I did wrong. I read in a thread about doing the NextResponse in the return statement, but even that didn't work.
The error message I get:
- Error TypeError: Cannot read property of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:261:61) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I would say the problem is related tothis question.
Your last two
return NextResponse...
are called inside thetransporter.sendMail()
callback, so they will not be retrieved from thePOST()
function return.UseNodemailer's ability to return promisesinstead of using callback functions...
Another way is to convert the Nodemailer's callback into a promise, although in my opinion this is not concise enough