Sendgrid 405 Error Method Not Allowed in Next.js

40 Views Asked by At

I'm about to go nuts, I'm trying to capture my leads via a custom form and send them over to a Sendgrid's contact's list but running into the 405 method not allowed error, even though it's a POST which IS accepted by their endpoint. Please, any input is much appreciated.

This is my page.tsx handleSubmit function (if I console log my data it is captured correctly):

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        try {
            const result = await axios.post(`/api/sendgrid`, {
                data
            })
            if(result.status === 200) {
                setDataSent(true)
            }
        } catch(err) {
            console.log("Error sending data to Sendgrid", err)
        }
}

And this is my app/api/sendgrid/route.ts:

import axios from "axios";
import { NextApiRequest, NextApiResponse } from "next";
import { NextResponse } from "next/server";

export async function POST(req: NextApiRequest, res: NextApiResponse) {
  console.log("REQUEST_BODY", req.body); //doens't get console logged in terminal
  if (req.method === "POST") {
    try {
      const data = await axios.post(
        `https://api.sendgrid.com/v3/marketing/contacts`,
        {
          "contacts": [{ 
            email: req.body.email,
            "custom_fields": {
              full_name: req.body.full_name,
              budget: req.body.budget,
              needs: req.body.needs
            }
        }],
          list_ids: [process.env.SENDGRID_MAILING_ID],
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
          },
        }
      );
      return NextResponse.json({ data })
    } catch (err) {
      console.error("Error in SendGrid request:", err);
      return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }) //throws this error and the 405 Method not Allowed
    }    
  }
}

I do have those custom fields configured in my Sendgrid, my domain is authenticated and verified, my .env are correct... yet I'm totally lost as per why it doesn't go through. I know I might be overlooking something obvious but it's my first time working with Sendgrid so thanks a lot everyone for your help!

  • Tried change my method to PUT - didn't work, with PUT it returns the error 400 BAD REQUEST and my custom_fields as an empty object, even though I double checked they are captured - can this be the issue?.
  • Tried commenting out the custom fields and only doing the default email - didn't work

This is Next.js

0

There are 0 best solutions below