Search code examples
javascriptnext.jsfetch-apivercelproduction-environment

Nextjs API folder call - 500 error in production


I have an API folder in my next.js app for some server side endpoints:

import { NextApiRequest, NextApiResponse } from 'next'

import Cors from 'cors'

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

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a 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: 'Teszt',
                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 call the endpoint, in development it works perfectly:

But in production I got 500 error. (deployed to vercel)

Error in the console on vercel:

[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 other configuration should I add to my next.config file to make it work, I am beginner with this API.

UPDATE:
This solved my problem... https://github.com/vercel/next.js/issues/34844


Solution

  • The problem was with the .js file wrong import: Same issue here: https://github.com/vercel/next.js/issues/34844#issuecomment-1055628706

    TLDR: Remove the import { NextApiRequest, NextApiResponse } from "next";