Next.js Discord

Discord Forum

api routes not working on build on vercel only

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hey all,

In my nextjs project i have 2 api routes, submit-email and contact.

in dev, both work as expected.
in build on my dev machine, again, both work as expected.
in build on vercel, it contact works, and submit-email doesnt.

They have identical code, one is litteraly almost a copy of the other
I have been troubleshooting this all night to no avail, could anyone help?

component.tsx
[...]
import { Form, useForm, SubmitHandler } from "react-hook-form";

export function Form() {

interface FormInputs {
  email: string;
}

  const [waiting, setWaiting] = useState(false);

const {
  register,
  handleSubmit,
  formState: { errors },
} = useForm<FormInputs>();

const onSubmit: SubmitHandler<FormInputs> = async (data) => {
  setWaiting(true);
  try {
    const response = await fetch("/api/submit-email", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error("Network response was not ok");
      setWaiting(false);
      alert("Error submitting form");
    } else {
      alert("form submitted successfully!");
      setWaiting(false);
    }

    const result = await response.json();
    console.log(result); // Handle the response from the server
  } catch (error) {
    console.error("Error submitting form:", error);
    alert(t("Error submitting form"));
    setWaiting(false);
  }
};
[...]

12 Replies

Spectacled bearOP
and submit-email/route.tsx
import { NextRequest, NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

export async function POST(req: NextRequest) {
  const { email } = await req.json();

  console.log("inside api route now...");

  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: parseInt(process.env.SMTP_PORT ?? '587', 10),
    secure: process.env.SMTP_PORT === '465',
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });

  const mailOptions = {
    [...]
  };

  const mailOptionsCopy = {
    [...]  
  };


  try {
    await transporter.sendMail(mailOptions);
    await transporter.sendMail(mailOptionsCopy);
    return NextResponse.json({ message: 'Form submitted successfully!' });
  } catch (error) {
    console.error('Error sending email:', error);
    return NextResponse.json({ message: 'Error sending email' }, { status: 500 });
  }
}

This one doesnt work on vercel, still works on my local machine...
Netherland Dwarf
@Spectacled bear
What does the logs say
On your vercel if you check for eeror logs
Error*^
Also
Its best to always validate your env before using them otherwise calll exit() or return a response with 500 if they dont exist
Something liek
If(!process.env.TOKEN || …)
Console.log( env not defined)
Return NextResponse( and add http status 500 and error: internal server error”
Spectacled bearOP
i managed to fix it, im not sure how
i made a bunch of changes and was making checks on build but locally
then i decided to check on vercel as well
and this time it worked
so i let it be for now
rn im thinking the most logical explanation is i forgot to commit something at some point
and then when i did that last commit it commited that something as well
unstaged changes mb? idk
rn im just refining some css