I’ve deployed a nextjs app on render. When attempt to use /api, it instead routes to /undefined. why is this?
Here is my code:
src/app/cart.js:
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'}},
{ withCredentials: true });
window.location.href = response.data.url;
} catch (error) {
console.error("error in cart async: ", error);
alert('Something went wrong during checkout');
}
};
src/app/api/route.js:
import express, { request } from 'express';
import bodyParser from 'body-parser';
import { Client, Environment } from 'square';
import {NextRequest, NextResponse} from 'next/server'
import axios from 'axios'
console.log("entered API")
const client = new Client({
accessToken: process.env.SQUARE_ACCESS_TOKEN,
environment: Environment.Production
});
export async function POST(req, res) {
console.log("POST request received");
try {
const { cartItems, totalCost} = 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 });
}
};
It may be worth noting that i did not follow this guide Deploy a Next.js App | Render Docs to deploy my nextjs app, i simply grapped it from a github repo. This issue only occurs on render