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";