Adam Ilčišák
Adam Ilčišák

Reputation: 647

Nextjs deployment on Vercel - api requests return 500, works on localhost

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.

Upvotes: 5

Views: 1262

Answers (1)

Adam Ilčišák
Adam Ilčišák

Reputation: 647

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.

Upvotes: 5

Related Questions