0

So I have some models in my MongoDB database, which details I am trying to fetch via Mongoose in NextJS, everything works in development but in production the data is not being fetched. I have been trying to fix the error but it doesn't work, I am using server actions to fetch the data like this :

"use server";
import { jwtVerify } from "jose";
import mongoose from "mongoose";
import { cookies } from "next/headers";
import connectDB from "../db";
export const getUnverfiedSellers = async () => {
 try {
 connectDB();
 const cookie = await cookies();
 const token = cookie.get("token")?.value;
 if (!token) {
 return {
 message: "Unauthorized",
 };
 }
 const { payload } = await jwtVerify(
 token,
 new TextEncoder().encode(process.env.JWT_SECRET!)
 );
 if (!payload.sub || typeof payload.sub !== "string") {
 return {
 message: "Invalid token",
 status: 401,
 };
 }
 const sellersCollecrion = await mongoose.connection.db
 ?.collection("sellers")
 .find({
 isVerified: false,
 })
 .project({
 password: 0,
 __v: 0,
 isLoggedin: 0,
 role: 0,
 registerotp: 0,
 registerOtpExpiry: 0,
 otp: 0,
 });
 const sellers = await sellersCollecrion?.toArray();
 console.log("sellers unverfied", sellers);
 if (!sellers) {
 return {
 message: "No sellers found",
 };
 }
 return {
 sellers,
 message: "Sellers fetched successfully",
 status: 200,
 };
 } catch (error) {
 console.error("Error fetching sellers:", error);
 return {
 message: "Error fetching sellers",
 error: error,
 status: 500,
 };
 }
};
export const getAllBuyers = async () => {
 try {
 connectDB();
 const cookie = await cookies();
 const token = cookie.get("token")?.value;
 console.log("tokenB", token);
 if (!token) {
 return {
 message: "Unauthorized",
 };
 }
 const { payload } = await jwtVerify(
 token,
 new TextEncoder().encode(process.env.JWT_SECRET!)
 );
 if (!payload.sub || typeof payload.sub !== "string") {
 return {
 message: "Invalid token",
 status: 401,
 };
 }
 const buyerCollections = await mongoose.connection.db
 ?.collection("buyers")
 .find({})
 .project({
 password: 0,
 __v: 0,
 isLoggedin: 0,
 role: 0,
 registerotp: 0,
 registerOtpExpiry: 0,
 otp: 0,
 });
 const buyers = await buyerCollections?.toArray();
 console.log("all buyers", buyers);
 if (!buyers) {
 return {
 message: "No buyers found",
 };
 }
 return {
 buyers,
 message: "Buyers fetched successfully",
 status: 200,
 };
 } catch (error) {
 console.error("Error fetching buyers:", error);
 return {
 message: "Error fetching buyers",
 status: 500,
 };
 }
};

The data is being fetched in development, the build process didn't give any errors too, but in production error in production

error-production

Then I am fetching them on frontend :

import { getAllBuyers } from "@/lib/data-access-layer";
import React from "react";
import BuyersTable from "./BuyerTable";
import { BuyerInterface } from "@/types/interfaces";
const ShowBuyers = async () => {
 const rawData = await getAllBuyers();
 // Convert MongoDB ObjectIds to strings
 const serializedBuyers = rawData.buyers!.map((buyer) => ({
 ...buyer,
 _id: buyer._id.toString() as string,
 }));
 return (
 <div className="flex flex-col gap-4">
 <h1 className="text-xl font-bold">Buyers</h1>
 <BuyersTable buyers={serializedBuyers as BuyerInterface[]} />
 </div>
 );
};
export default ShowBuyers;

On the dashboard page :

import SectionCards from "@/components/dashboard/SectionCards";
import LoadingSkeleton from "./loading";
import React, { Suspense } from "react";
import ShowUnverfiedSellers from "@/components/seller/ShowUnverfiedSellers";
import ShowBuyers from "@/components/buyer/ShowBuyers";
//import OrdersChart from "@/components/dashboard/OrderChart";
export const dynamic = "force-dynamic";
const DashboardPage = async () => {
 return (
 <div className="ml-20 mb-10 pt-2.5 flex flex-col gap-y-6">
 <h1 className="text-2xl font-bold">Dashboard</h1>
 <Suspense fallback={<LoadingSkeleton />}>
 <div className="w-full shrink-0">
 <SectionCards />
 </div>
 </Suspense>
 <Suspense fallback={<LoadingSkeleton />}>
 <div className="w-full shrink-0">
 <ShowBuyers />
 </div>
 </Suspense>
 {/* <Suspense fallback={<LoadingSkeleton />}>
 <div className="w-full shrink-0">
 <OrdersChart />
 </div>
 </Suspense> */}
 <Suspense fallback={<LoadingSkeleton />}>
 <div className="w-full shrink-0">
 <ShowUnverfiedSellers />
 </div>
 </Suspense>
 </div>
 );
};
export default DashboardPage;

The error persists, I checked my .env in prod and they are perfect too, It would be of great help if someone can help me fix it. Thank you.

Hamed Jimoh
1,4682 gold badges10 silver badges22 bronze badges
asked May 22, 2025 at 10:39
2
  • update: I tried awaiting the connectDB() function, I still get the same error Commented May 22, 2025 at 14:22
  • Have you already set the appropriate next.config settings for mongoose? Using Mongoose With Next.js Commented May 22, 2025 at 21:42

1 Answer 1

0

Okay so I fixed it, The issue was mongoose didn't support edge run time, The work around is to do the following :

npm install next@canary 

Add the following in your next.config.ts:

import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
experimental: {
esmExternals: "loose", // <-- add this
nodeMiddleware: true,
},
serverExternalPackages: ["mongoose"], // <-- and this
};
export default nextConfig;

That fixed the issue.

answered May 23, 2025 at 5:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.