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?