From c1b568a6b72e528f839787d8dee53294205a5b86 Mon Sep 17 00:00:00 2001 From: Harshit-Mishra2212 Date: Tue, 26 May 2026 02:30:59 +0530 Subject: [PATCH] fix: defer MongoClient init to request time to fix build crash --- src/app/api/cohort/route.ts | 39 ++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/src/app/api/cohort/route.ts b/src/app/api/cohort/route.ts index d943ffb..c12d9a0 100644 --- a/src/app/api/cohort/route.ts +++ b/src/app/api/cohort/route.ts @@ -1,19 +1,40 @@ -// app/api/cohort/route.ts import { NextResponse } from 'next/server'; import { MongoClient } from 'mongodb'; +let cachedClient: MongoClient | null = null; -const uri = process.env.MONGO_URI!; -const client = new MongoClient(uri); -const dbName = 'cohortDB'; -const collectionName = 'cohortData'; +async function getClient(): Promise { + if (cachedClient) return cachedClient; + + const uri = process.env.MONGO_URI; + if (!uri) { + throw new Error('MONGO_URI environment variable is not set'); + } + + const client = new MongoClient(uri); + await client.connect(); + cachedClient = client; + return client; +} + +const DB_NAME = 'cohortDB'; +const COLLECTION_NAME = 'cohortData'; export async function GET() { try { - await client.connect(); - const data = await client.db(dbName).collection(collectionName).find({}).toArray(); + const client = await getClient(); + const data = await client + .db(DB_NAME) + .collection(COLLECTION_NAME) + .find({}) + .toArray(); + return NextResponse.json(data); } catch (error) { - return NextResponse.json({ error: 'Failed to fetch data' }, { status: 500 }); + console.error('Failed to fetch cohort data:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Failed to fetch data' }, + { status: 500 } + ); } -} +} \ No newline at end of file