Flaky endpoints with Next.js app deployed to Vercel

I deployed a next.js app to Vercel and am experiencing flaky endpoints.

The 5 endpoints are defined in pages/api/... and work perfectly in localhost – and are also called infrequently in localhost.

In the deployment, the endpoints sometimes returns a Internal error, status 500. I am using middleware and am wondering if that could be causing the issue.

import cache from 'express-redis-cache';

const c = cache();

const run = (req, res) => (fn) => new Promise((resolve, reject) => {
  fn(req, res, (result) =>
      result instanceof Error ? reject(result) : resolve(result)
  )
})


const handler = async (req, res) => {
  const middleware = run(req, res);
  await middleware(cors());
  await middleware(c.route({
      expire: 30
  }))
  /** validate req type **/
  if (req.method !== 'GET') {
    res.status(400).json({});
    return;
  }
...

I also tried removing the express-redis-cache for one of the endpoints:

import Cors from 'cors';
import axios from 'axios';

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

function runMiddleware(req, res, fn) {
    return new Promise((resolve, reject) => {
      fn(req, res, (result) => {
        if (result instanceof Error) {
          return reject(result)
        }

        return resolve(result)
      })
    })
  }

const handler = async (req, res) => {
    console.log('raised call', req);
    await runMiddleware(req, res, cors);

But they are all flaky — seems like every other call works. Its between status 500 and it working.

Another followup to this is – I used react hooks to make sure API calls were only made when necessary. Is there a reason why so many repeat calls are being made when these calls are not made on localhost? For instance, I have 4 endpoints that only need to get called once each per page load but in the deploy they are getting called many times.