Next.js MongoDB Not Working on Deployment
Answered
American black bear posted this in #help-forum
American black bearOP
I am building an application with Next 14 app router, and MongoDB. I am using the official MongoDB driver. Here's the config:
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:
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";Answered by Ray
maybe try, not sure if it makes different
const db = (await clientPromise).db(${process.env.DATABASE_NAME});29 Replies
American black bearOP
Nothing helpful. Getting status 200
status 200 on the route handler?
American black bearOP
Yes
what response do you get if you visit it?
American black bearOP
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.
do you have correct variable set?
process.env.DATABASE_NAMEAmerican black bearOP
Yes. It's the same as the local environment
maybe try put the database name directly in the route handler and see if it works
American black bearOP
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!
ah
maybe try, not sure if it makes different
const db = (await clientPromise).db(${process.env.DATABASE_NAME});Answer
Peterbald
Can you show me your vercel logs?
@Peterbald Can you show me your vercel logs?
American black bearOP
Log is pretty clear. Not sure it this will help.
@Ray maybe try, not sure if it makes different
ts
const db = (await clientPromise).db(${process.env.DATABASE_NAME});
American black bearOP
Let me try this one
Peterbald
if you use direct url instead of env, it works properly?
So you can get the data from database?
American black bearOP
Yes. But I also added a console log for the ENV, and it showed the ENV properly in the logs!
Peterbald
Where did you keep mogoDB connection as a global variable?
And where are you hosting online mongoDB?
@Peterbald And where are you hosting online mongoDB?
American black bearOP
Using Atlas
Peterbald
very weird.
try fetching directly from server component, if it doesnt require any client data. ?
@Ray maybe try, not sure if it makes different
ts
const db = (await clientPromise).db(${process.env.DATABASE_NAME});
American black bearOP
This worked by the way! 🤔