Baxter John
Baxter John

Reputation: 11

Nextjs api works on local but gives error 405 on vercel production

I am trying to deploy an ecommerce site on vercel that uses a square create payment api. It works perfectly on my local server, but when deployed, I get:

POST https://mySite.vercel.app/api 405 (Method Not Allowed)
error in cart async:  V {message: 'Request failed with status code 405', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

this is my Api call:

const checkout = async () => {
  try {
    const totalCost = cartItems.reduce((total, item) => total + item.product.price, 0);
    const items=stringifyCart()
    const response = await axios.post('/api',{cartItems: items, totalCost: totalCost},
      { headers: {'Content-Type': 'application/json'}});
    window.location.href = response.data.url;
  } catch (error) {
    console.error("error in cart async: ", error);
    alert('Something went wrong during checkout');
  }
};

and my api/route.js (although i dont think the server even reaches this function):

const client = new Client({
  accessToken: process.env.SQUARE_ACCESS_TOKEN,
  environment: Environment.Production
});

export async function POST(req, res) {
  try {
    const { cartItems, totalCost, address } = await req.json();
    const response = await client.checkoutApi.createPaymentLink({
      idempotencyKey: new Date().getTime().toString(),
      quickPay: {
        name: cartItems,
        priceMoney: {
          amount: totalCost * 100,
          currency: 'USD'
        },
        locationId: process.env.SQUARE_LOCATION_ID
      },
      checkoutOptions: {
        askForShippingAddress: true,
        acceptedPaymentMethods: {
          applePay: true,
          googlePay: true,
          cashAppPay: true,
          afterpayClearpay: true
        }
      }
    });

    return NextResponse.json({ url: response.result.paymentLink.url }, { status: 200 });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
};

I am currently on a vercel hobby account, but the same issue occcured on a paid account trial and when deployed to github pages. using npm run dev on my local, everything works as it should

Upvotes: 1

Views: 393

Answers (2)

Aquila Afuadajo
Aquila Afuadajo

Reputation: 1

I encountered a similar issue recently, and after some research, I found a potential cause that might help you out.

"It appears the problem could be related to static rendering. When Next.js statically renders a page, it assumes that there's no need for dynamic data fetching or server-side processing. As a result, it delivers a static HTML page from the CDN/edge server, which means your outgoing POST request might not be processed as expected."

Here's a relevant thread on GitHub that discusses this issue: GitHub Issue Thread.

To resolve this, I switched back to server-side rendering (SSR) by removing the output option from my next.config.js and redeployed the application. This change allowed the page to be rendered dynamically, and the POST requests started working as expected.

Give this a try and see if it resolves the issue for you!

Upvotes: 0

rsandor
rsandor

Reputation: 31

Seems like you have .env.production and .env.dev.

I came across issues with the environment being set correctly regardless of selected environment.

Try doing something like this:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "cp .env.dev .env && next dev",
    "build": "cp .env.prod .env && next build",
    "build:dev": "cp .env.dev .env && next build",
    "build:prod": "cp .env.prod .env && next build",
    "start": "next start",
    "lint": "next lint",
    "test": "vitest",
    "test-ui": "vitest --ui --coverage",
    "coverage": "vitest run --coverage",
    "vitest-preview": "vitest-preview"
  },
// rest of package.json

Upvotes: 0

Related Questions