The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directly interact with the database. These functions are then invoked within the getStaticProps() and getStaticPaths() methods of the respective components. Below is the implementation found in controllers.js:

import clientPromise from "./clientPromise";

let client;
let db;

(async function () {
  // We must place the await inside this async function that immediately executes instead of at the top level.
  client = await clientPromise;
  db = client.db("dev"); // using development database
})();

// Query the "technologies" collection:
export async function getTechnologies() {
  const technologies = await db
    .collection("technologies")
    .find({})
    .toArray();
  return JSON.parse(JSON.stringify(technologies));
}

// Query the "projects" collection:
export async function getProjects() {
  const projects = await db
    .collection("projects")
    .find({})
    .toArray();
  return JSON.parse(JSON.stringify(projects));
}

Here's a snippet showcasing how I'm leveraging these controllers:

// Working perfectly fine:
export async function getStaticProps() {
    const projects = await getProjects();

    return {
        props: { projects: projects },
    }
};

// Causing an error:
export async function getStaticPaths() {
    const projects = await getProjects();

    return {
        paths: [{ params: {_id: "placeholder"} }],
        fallback: false,
    };
}

The encountered error indicates that db is undefined and hence the method "collection" cannot be utilized on it. My analysis suggests that the anonymous async function, intended to execute immediately, does not run when calling getProjects() within getStaticPaths(), leading to db remaining undefined and causing the error. Interestingly, everything works as expected when invoking getProjects() in getStaticProps(). What could possibly be causing this issue?

Answer №1

In the event that db is not defined when you call getProjects, there are two potential scenarios:

  1. You are executing getProjects before await clientPromise has been resolved.
  2. The value returned by clientPromise is actually undefined.

Without more information, it is difficult to troubleshoot the second possibility, so let's focus on the first one for now.


(async function () {
  // Since await cannot be used at the top level/module scope, we need to use it inside an immediately invoked async function like this.
  client = await clientPromise;
  db = client.db("dev"); // using development database
})();

Your current setup includes an async function that returns a promise, which could be leveraged to determine when the result becomes available.

However, instead of managing the promise, you have chosen a fire-and-forget approach that relies on timing-dependent side effects.

Consider utilizing the returned promise for better control over timing.

const db = (async function () { 
    const client = await clientPromise;
    const devdb = client.db("dev");
    return devdb;
}();

With this change, db will immediately resolve to the desired value rather than remaining as undefined and potentially changing later.

Remember to adjust the rest of your module accordingly. For instance:

const projects = await db
    .collection("projects")

will need to be updated to:

const devdb = await db;
const projects = devdb.collection("projects")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to toggle visibility of a Bootstrap modal using VueJS (using CDN) without displaying the overlay

I have integrated VueJS into a single page using the CDN, which prevents me from utilizing bootstrap-vue. The functionality to display and hide a modal based on the value of the showModal data is currently working. However, the gray overlay surrounding th ...

Exploring the differences in performance between React hooks and React classes

Currently, I am delving into understanding React hooks and could use some assistance with comprehending whether every time a React function renders, the hook state resets. Below is a brief example related to fixing a header on scroll: class Header extends ...

Having difficulty showing the successful JSON output in either the view or an alert

In my CodeIgniter project, I have three input fields named name, emp_id, and crm_id. I enter the id value and send it to the controller via AJAX and JSON to retrieve all information related to that id. The issue is that while I can see the correct output i ...

Identifying changes in Android volume settings via Progressive Web App (PWA)

After creating a PWA with React, I generated a TWA .apk using pwabuilder.com. While having a muted video playing on my screen, I am looking for a way to unmute the video when the user presses the volume change buttons on their Android mobile device. Is th ...

What is the method to utilize the process.env object from within an imported npm package in the importing class?

In my React app, I used dotenv to set process.env variables for each component. When all components were in the same source code repo and imported via '../component/component_name', accessing these variables was easy using process.env.variable_na ...

What is the process for tallying checked checkboxes in a functional component using React Native?

The Whole Code is Right Here Within this code, you will find two flat lists: one displaying category names and the other showing their subcategories with checkboxes. I am looking to implement a feature where if a user checks multiple or just one checkbox ...

transferring information from Node.js/MongoDB to the front-end (invisible in the browser)

I am trying to retrieve data from a mongodb database and pass it to the front-end. The function I have written works in the console, where I can see an array containing elements. However, when I try to view it in the browser, it shows undefined. I am worki ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Refresh your jQuery function without the need to reload the entire page

Is there a way to update a function's parameters without reloading the entire page? For instance, if I modify the 'style' dropdown value as shown in the URL image, can it be passed to the accordion function so that the accordion's color ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

What is the most effective method for transferring data to a concealed input field?

I currently have a webpage with dual forms - one on the main page and another within a Bootstrap modal. The primary form includes fields like "Neck, Chest, Waist," while the modal's form only has an email field. To streamline the submission process, ...

Encountering a 'unknown column' error while using MySQL on a Windows operating system

A query is being executed on Node.Js with MySQL, resulting in the following: SELECT COUNT(DISTINCT t.uid) AS usersCount, COUNT(*) AS workingDaysCount FROM ( SELECT d.date, u.id AS uid, CASE TIMESTAMPDIFF(day, SUBDATE(d.date, WEEKDAY(d.date) ...

Run a Python function in Django without any feedback

Currently, I am utilizing Django for a project and I find myself in a situation where I need to carry out certain functions based on user input. If the action requires displaying new values, I know how to handle that. However, when I simply need to execute ...

Preventing direct URL access with Angular redirects after refreshing the page

My website allows users to manage a list of users, with editing capabilities that redirect them to the /edit-user page where form information is preloaded. However, when users refresh the page with F5, the form reloads without the preloaded information. I ...

Problem arises when attempting to slice an array that is defined in the parent component

Seems like a simple mistake, but here's what happened: In the main parent component, I have an array defined: ... <object-list-grid v-bind:objects="objectsList" ></object-list-grid> ... data() { return { ... ...

Sending an AJAX request to a Symfony controller's URL

Recently, I encountered an issue with integrating a piece of code from backend.php into my Symfony controller. In the initial setup, I had an AJAX call in a JS file that interacted with backend.php to test some functionality. function postRequest() { var ...

numerous sections within a solitary webpage

I need to implement multiple tabs on a single page, how do I modify the code to make this possible? Take a look at the codepen for reference. Here is the jquery code I have written so far: var tabs = $(".tabContainer ul li a"); $(".tabConten ...

How come the styles in my CSS file aren't being applied to my images based on their class or ID?

When I apply a className or id to my img tag in my JavaScript (using React.js) and then add a style that references that id or class, the style does not get applied. However, when I do the same for a div, everything works perfectly fine. <--JavaScript- ...

An unexpected token was discovered by Jest: export { default as v1 } when using uuid

While working on writing Jest tests for my React component in a Monorepo, I encountered an error while running the Jest test. ● Test suite failed to run Jest encountered an unexpected token... ...SyntaxError: Unexpected token 'export' ...