5

I deployed my Nextjs app to Vercel and my api calls are failing with response 500, even though it works on localhost. I can get initial load with getStaticProps, so I believe connection to DB is OK.

My getStaticPaths function which works correctly looks like that:

export async function getStaticProps() {
  dbConnect();
  const properties = await Property.find({
    deletedAt: { $exists: false },
    archivedAt: { $exists: false },
  })
    .sort({ refreshed: -1 })
    .limit(itemsPerPage);
  const propertiesCount = await Property.countDocuments(
    { deletedAt: { $exists: false }, archivedAt: { $exists: false } },
    { limit: 100 }
  );
  const pagesCount = Math.ceil(propertiesCount / itemsPerPage);

  return {
    props: {
      fetchedProperties: properties.map((property) => propertyToJson(property)),
      pagesCount: pagesCount,
    },
    revalidate: 5,
  };
}

However, when query changes, I call useEffect hook like that:

useEffect(() => {
    if (Object.keys(query).length > 0) {
      (async () => {
        const filteredProperties = await fetch(
          process.env.NEXT_PUBLIC_BASE_URL +
            '/api/properties?' +
            new URLSearchParams(query)
        );
        const res = await filteredProperties.json();

        if (res.status === 200) {
          setProperties(res.properties);
        } else {
          //show error
          console.log('error');
        }
      })();
    }
  }, [query]);

and this always return error (works on localhost). My pages/api/properties/index.js file looks like that:

import dbConnect from 'utils/dbConnect';
import Property from 'models/Property';
import { propertyToJson } from 'utils/helpers';

const handler = async (req, res) => {
  console.log('req:', req);
  const { method } = req;
  dbConnect();
  if (method === 'GET') {
    const { price } = req.query;

    let queryCond = {};
    if (price) {
      queryCond.price = { $lte: price * 1 };
    }
    console.log('queryCond:', queryCond);

    try {
      const properties = await Property.find(queryCond).exec();
      console.log('properties:', properties);

      res.status(200).json({
        status: 200,
        properties: properties,
      });
    } catch (err) {
      res.status(500).json(err);
    }
  }
};

export default handler;

Moreover, I am not able to see console.log from that api file anywhere. Not in Vercel function logs, not in my terminal when running vercel dev --debug. I have a feeling, that the request is not even getting to that api/properties/index.js file...

I would really appreciate if you can help me with the issue, but I will appreciate even more, if you can point out, how to debug these api files in effective way. Thanks.

Sergey Panteleev
  • 122
  • 1
  • 1
  • 10
Adam Ilčišák
  • 627
  • 6
  • 14
  • Do you get any error in Vercel's function logs at all in regards to the API route? If the API is returning a 500, there must be an error happening somewhere, which should be visible in the logs. – juliomalves Aug 20 '22 at 22:05
  • Thank you for looking into this. There are no errors in funtion logs, the only error I can see is in tho console. You can find the project here: https://portalprenajmu2.vercel.app/ There is a filter "Price" at the top of the listing, which is triggered after change. The error says - Uncaught (in promise) SyntaxError: Unexpected token '<', " – Adam Ilčišák Aug 21 '22 at 08:25
  • Do you still need help? It seems the site from the URL is working fine when changing the price filter. You can share your solution as an answer and accept it. – diedu Aug 22 '22 at 23:47

1 Answers1

5

I figured this out. There were two problems with my approach:

  1. Code snippets I provided were just part of the more complex code. There was a part for "POST" method, which I ommited in the question and there was an import of import { adminAuth } from 'config/firebase-admin' where env variable was configured incorrectly. I supposed that this part shouldn't be problem as I was not calling this part of the method.
  2. Of course, I tested even with the code in the question as it is, but it looks like, it was probably cached in my browser and it was reflecting older builds. For every build on Vercel, there are 3 urls generated and it is probably the best to go with the one, which includes token- so it is unique for the build and there is no chance that you are looking at cached old code.
Adam Ilčišák
  • 627
  • 6
  • 14