#Next.js MongoDB Not Working on Deployment

31 messages · Page 1 of 1 (latest)

vapid shard
#

I am building an application with Next 14 app router, and MongoDB. I am using the official MongoDB driver. Here's the config:

import { MongoClient, MongoClientOptions } from "mongodb";

if (!process.env.MONGODB_URI) {
  throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}
const IS_DEVELOPMENT = process.env.NODE_ENV === "development";

const uri = process.env.MONGODB_URI;
const options: MongoClientOptions = {};

let client;
let clientPromise: any;

if (IS_DEVELOPMENT) {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  let globalWithMongo = global as typeof globalThis & {
    _mongoClientPromise?: Promise<MongoClient>;
  };

  if (!globalWithMongo._mongoClientPromise) {
    client = new MongoClient(uri, options);
    globalWithMongo._mongoClientPromise = client.connect();
  }
  clientPromise = globalWithMongo._mongoClientPromise;
} else {
  client = new MongoClient(uri, options);
  clientPromise = client.connect();
}

export default clientPromise;

This works fine in the localhost. But for some reason, the database is not connecting when deployed to Vercel. I have added 0.0.0.0 to IP whitelist. But the issue is still the same. I might be missing some basic stuff here. Can someone point me out?

Here's a dummy route:

export async function GET(request: NextRequest, response: NextResponse) {
  try {
    const db = (await clientPromise).db(process.env.DATABASE_NAME);

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

    return NextResponse.json(
      {
        message: "Collection fetched successfully",
        success: true,
        data: clc,
      },
      {
        status: 200,
      }
    );
  } catch (error) {
    return NextResponse.error();
  }
}

export const dynamic = "force-dynamic";
kind prawnBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

shut ether
vapid shard
#

Nothing helpful. Getting status 200

shut ether
#

status 200 on the route handler?

vapid shard
#

Yes

shut ether
#

what response do you get if you visit it?

vapid shard
#

But the response object where it should contain the details is empty.

#
{
message: "Data fetched successfully",
success: true,
data: [ ]
}

Here's what the API is returning on the deployment. But getting the data object properly on localhost, with the same ENVs.

shut ether
#

do you have correct variable set?

#

process.env.DATABASE_NAME

vapid shard
#

Yes. It's the same as the local environment

shut ether
#

maybe try put the database name directly in the route handler and see if it works

vapid shard
#

Trying it out now.

#

This worked! However, I've set the env properly! Not sure what I did wrong!

#

I also console logged the ENV, and it is showing in the Vercel logs!

shut ether
#

ah

#

maybe try, not sure if it makes different

const db = (await clientPromise).db(${process.env.DATABASE_NAME});
rare shoal
#

Can you show me your vercel logs?

vapid shard
rare shoal
#

if you use direct url instead of env, it works properly?

#

So you can get the data from database?

vapid shard
#

Yes. But I also added a console log for the ENV, and it showed the ENV properly in the logs!

rare shoal
#

Where did you keep mogoDB connection as a global variable?

#

And where are you hosting online mongoDB?

vapid shard
rare shoal
#

very weird.

pine wagon
#

try fetching directly from server component, if it doesnt require any client data. ?

shut ether