2

I'm trying to connect to my sample mongoDB collection using getInitialProps inside my _app.js but I'm having this issue of Module not found: Can't resolve 'dns'

_app.js

import { connectToDatabase } from '../middlewares/mongodb';

function MyApp({ Component, pageProps, prop }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  );
}

MyApp.getInitialProps = async (appContext) => {
  const { db } = await connectToDatabase();
  const data = await db
    .collection('listingsAndReviews')
    .find({})
    .limit(10)
    .toArray();

  const prop = JSON.parse(JSON.stringify(data));
  return { ...prop };
};

1 Answer 1

3

getInitialProps runs on the server during initial page load and on the client during client navigations. As such getInitialProps should contain isomorphic code - code able to run in both server and client environments.

In your case you have code that requires a Node.js environment (server), and as such will fail when running on the browser.


A possible solution is to move your database fetching logic to an API route.

// pages/api/listings

export const fetchDbData = async () => {
    const { db } = await connectToDatabase();
    const data = await db
        .collection('listingsAndReviews')
        .find({})
        .limit(10)
        .toArray();
    return JSON.parse(JSON.stringify(data));
}

export default async (req, res) => {
    const data = await fetchDbData()
    res.status(200).json(data)
}

In your getInitialProps you can then call the fetchDbData logic directly when it's running on the server, or make an API call when it's running on the client.

import { fetchDbData } from './api/listings';

MyApp.getInitialProps = async (appContext) => {
    let prop;

    if (appContext.ctx.req) { // Checks if running on server
        prop = await fetchDbData(); // Call logic directly on the server
    } else {
        const res = await fetch('/api/listings'); // Make API call on the client
        prop = await res.json();
    }

    return { ...prop };
};

This ensures your database fetching logic will always run in the server environment.

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

6 Comments

The problem also is on my MongoDB connection inside my middleware folder. If I import the connection in the root file inside the pages folder, it returns DNS error.
You only need to import it in your API route.
Sorry, i overlook it. but it's working now! Thanks again!
Usually, the call to the database would occur on each page request/transition as getInitialProps runs during that time. However, it will run at build time only if your pages are statically generated with getStaticProps - see _app.getInitialProps is not called on every request.
this helped me so much, simple elegant, perfect! thanks!
|

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.