Encountering a 500 error in production when making a call to the Next.js API

I have a dedicated API folder within my next.js application to handle server-side endpoints:

import { NextApiRequest, NextApiResponse } from 'next'

import Cors from 'cors'

// Setting up the CORS middleware
const cors = Cors({
  methods: ['GET', 'HEAD', 'POST'],
  origin: '*',
  optionsSuccessStatus: 200,
})

// Function to run middleware before continuing
// And handling errors in middleware
function runMiddleware(req, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}

export default async (req, res) => {
  await runMiddleware(req, res, cors)

  const POSKEY = process.env.POSKEY
  const PAYEE = process.env.PAYEE

  const { currency, url, locale, price } = req.body
  const currentUrl = url

  const apiResult = await fetch(
    'https://api.test.barion.com/v2/Payment/Start',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': 3495,
      },
      body: JSON.stringify({
        PosKey: POSKEY,
        PaymentType: 'Immediate',
        GuestCheckout: true,
        FundingSources: ['All'],
        Currency: currency,
        RedirectUrl: currentUrl,
        CallbackUrl: currentUrl,
        Locale: locale,
        Transactions: [
          {
            Payee: PAYEE,
            Total: price,
            Items: [
              {
                Name: 'Test',
                Description: 'Test item comment',
                Quantity: 1,
                Unit: 'pc',
                UnitPrice: 1,
                ItemTotal: 1,
                SKU: 'SM-01',
              },
            ],
          },
        ],
      }),
    }
  )
    .then((result) => {
      return result.json()
    })
    .catch((error) => {
      console.error(error)
    })

  res.status(200).json({
    url: apiResult.GatewayUrl
  })
}

When I trigger the endpoint, it works perfectly in the development environment:

However, I encountered a 500 error in the production environment. (deployed on Vercel)

Error message in the Vercel console:

[POST] /apigateway/ 23:30:28:53
2022-06-27T21:30:28.595Z e8c57750-4647-4e7a-b62e-6221abc141ac ERROR Error: Cannot find module
'/var/task/node_modules/next/dist/server/next.js'.
Please verify that the package.json has a valid "main" entry
at tryPackage (internal/modules/cjs/loader.js:321:19)
at Function.Module._findPath (internal/modules/cjs/loader.js:534:18)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:888:27)
at Function.Module._load (internal/modules/cjs/loader.js:746:27)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:101:18)
at Object.5199 (/var/task/.next/server/pages/api/gateway.js:20:39)
at __webpack_require__ (/var/task/.next/server/webpack-api-runtime.js:25:42)
at __webpack_exec__ (/var/task/.next/server/pages/api/gateway.js:109:39)
at /var/task/.next/server/pages/api/gateway.js:110:28 { code: 'MODULE_NOT_FOUND', path:
'/var/task/node_modules/next/package.json', requestPath: 'next' }
RequestId: e8c57750-4647-4e7a-b62e-6221abc141ac Error: Runtime exited
with error: exit status 1 Runtime.ExitError

What additional configuration settings should I include in my next.config file to resolve this issue, as I am new to working with APIs?

UPDATE:
I was able to resolve my issue by following the solution provided here: https://github.com/vercel/next.js/issues/34844

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am not forcing the Angular module to conform to my perspective

Hello, I am new to Angular and trying to experiment with some code. However, I seem to be stuck with the app.js file which is throwing an error: Uncaught SyntaxError: Unexpected token . Below is the structure of my application, which I obtained by cloning ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Can the parent document interact with Shadow DOM elements?

When it comes to user-created shadow DOM elements, this question focuses more on accessibility using the date input type: For instance, let's say there is a date input on a webpage. After some editing, the shadow DOM markup for this element (in Chrom ...

What is the best way to extract a CSS rule using PHP?

Below is an example of the stylesheet I am currently using: #thing { display: none; } I am looking to retrieve the value of the 'display' property using PHP instead of Javascript. While I know how to do this with Javascript, I would prefer to u ...

Finding the equivalent of BigInt from Javascript in C#

After creating a JavaScript script that converts a string to BigInt, I encountered a challenge while trying to find a C# equivalent function. The original conversion in Javascript looked like this: BigInt("0x40000000061c924300441104148028c80861190a0ca4088 ...

Stop the print dialog box from causing the page to refresh

I have implemented a print button for an invoice: </script> <!--Function for printing invoice--> <script> function printpage() { window.print() } </script> <button id="print" name="print" class="btn btn-info" onClick="pri ...

What causes certain files to be extremely large (bigger than 26MB) when exporting a page in nextJS?

After constructing a webpage using nextjs and utilizing next export to generate a static page, I noticed some files in the output directory with unusually large file sizes (refer to: https://i.sstatic.net/Z1v76.png) Interestingly, when uploaded to a serve ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

The radio button that disables other inputs only functions correctly for a single element when using Query Selector, but does not work with Query

I have attempted to develop a form section that is disabled when the user selects option A and enabled when they choose option B. document.getElementById('delivery').onclick = function() { var disabled = document.querySelectorAll(".dis ...

React: Error - Unable to use this.setState as a function

When attempting to pass a value from the Child Class to the Parent Class and set it in the Parent's state, I encounter the following error: TypeError: this.setState is not a function Parent Class class Header extends React.Component { constr ...

Is utilizing unregistered HTML elements for semantic purposes considered poor practice?

When it comes to styling and semantic purposes, I am considering using unregistered web components. This means utilizing tags like <t-card></t-card> without registering them with customElements.define. Surprisingly, the browser and stylesheets ...

Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this: [ { "title": "Fundamentals", "order": 1, "lessonRef": "fundamentals", "children": [ { "title": "History", "order": 1, "lesso ...

The array within the JSON object holds vital information [Typescript]

I have some data stored in an Excel file that I want to import into my database. The first step was exporting the file as a CSV and then parsing it into a JSON object. fname,lname,phone Terry,Doe,[123456789] Jane,Doe,[123456788, 123456787] Upon convertin ...

Tips for generating documentation using markdown within the docs directory on GitHub with the help of JavaScript

After browsing through numerous documentation websites, I have noticed that many of them share the same layout and features. This has led me to question whether there is a common library used by all these documentation sites. How do they achieve this unif ...

Error: The client must be connected before any operations can be performed in a production environment

import mongoose from "mongoose"; let connection = {}; async function establishConnection() { try { if (connection.isConnected) { console.log('Connected to database'); return; } if (mongoose.connections.length ...

Declining the request to incorporate an external website into my web platform

While checking the console errors in Google Chrome, I encountered the following error message: The page 'https://website.com' was blocked from framing because a higher-level ancestor violates the Content Security Policy directive: "frame-an ...

Guide to sending parameters to the method function of the Vue.js router

I am encountering an issue while trying to pass 'joke.id' as a parameter to the router: edit: function(joke) { this.$router.push({ '/edit/' + joke.id }); } The specific route in question is: {path: '/edit/:id', compone ...

Ways to manage a post request in Next.js

Attempting to establish a POST route within my api directory with next.js. After sending the data to the route, I am having difficulty parsing the data in order to properly store it in the database. What would be the most effective approach for managing ...

Determining the appropriate generic type in Typescript

In my code, there is a method designed to extend an existing key-value map with objects of the same type. This can be useful when working with database query results. export function extendWith< T extends { id: string | number }, O = | (T[" ...