0

I have a problem with NextJS. I get an error 'can`t resolve DNS' when I use getStaticProps and working with MongoDb. Why does this happen? Error occurs only when I have MongoDB code. Also code works in NextPages but not in React components.

export const getStaticProps: GetStaticProps = async (context) => {
  const client = await MongoClient.connect(
    "mongodb+srv://maciejtest:password0.vv1w4.mongodb.net/stockystocks?retryWrites=true&w=majority"
  );

  const db = client.db();

  const detailedAssetsCollection = db.collection("detailedAssets");
  const detailedAssets = await detailedAssetsCollection.find({}).toArray();

  console.log(detailedAssets);
  return {
    props: {
      assets: detailedAssets,
    },
  };
};
2
  • I believe it's throwing an error because you're importing a server-side only library into your client-side component. Instead, you should create a lib or util folder (outside of page) and import a connect utility function. See the official Nextjs with-mogodb example. Commented May 15, 2022 at 19:15
  • "code works in NextPages but not in react components" - getStaticProps only works in page components, it doesn't run in regular components. That would explain the error since the imports for the server-side code aren't being used, so Next.js also includes them in the client bundle. Commented May 15, 2022 at 21:44

1 Answer 1

0

I have been dreaded with this kind of a DNS issue from Atlas being on some wifis and had to fix that with VPN.

It may be the case for you as well. Try to test on another network if you have such, i.e. a mobile hotspot.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.