Trouble submitting JSON to airtable via nextjs route.ts

21 Views Asked by At

I'm trying to send data to airtable api via next js with the app route.

I'm using const data to store my json object.

When I send body: JSON.stringify({ fields: testData }),

I add a row to my airtable base, but no data.

Any thoughts?

Cheers.

//route.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest, res: NextResponse) {
  try {
    const data = await req.json();
    console.log(data);
    // This is what I'm recieving back from the console. but it's still not working. testData is working.
    // {
    //   Name: 'Test',
    //   Company: 'con',
    //   Challenge: 'dasd',
    //   Email: '[email protected]',
    //   Phone: '234234'
    // }
    const testData = {
      Name: "John",
      Company: "Fast Company",
      Challenge: "Here is my challenge",
      Email: "[email protected]",
      Phone: "+61400891285",
    };

    const response = await fetch(
      "https://api.airtable.com/v0/appiQwkJeriH8srVq/Entries",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.AIRTABLE_TOKEN}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ fields: testData }), // Airtable expects a "fields" object
      },
    );

    return NextResponse.json({ fields: testData }, { status: 200 });
  } catch (error) {
    console.log(error); // ---> I want to see what this prints server side, in your terminal
    const message = error instanceof Error ? error.message : "Unexpected Error";
    return NextResponse.json({ message }, { status: 500 });
  }
}

Here are my dependencies:

"dependencies": {
    "@radix-ui/react-form": "^0.0.3",
    "next": "14.1.0",
    "react": "^18",
    "react-dom": "^18",
    "vaul": "^0.8.9"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.1.0",
    "postcss": "^8",
    "prettier": "^3.2.4",
    "prettier-plugin-tailwindcss": "^0.5.11",
    "tailwindcss": "^3.3.0",
    "typescript": "^5"
  }

I expect a row with the data from my form to submit to airtable.

I can log my form to the console on the server, and submit dummy data no problem.

0

There are 0 best solutions below