Skip to content

fix: defer MongoClient init to request time to fix build crash#100

Open
Harshit-Mishra2212 wants to merge 1 commit into
seetadev:mainfrom
Harshit-Mishra2212:fix/cohort-route-build-crash
Open

fix: defer MongoClient init to request time to fix build crash#100
Harshit-Mishra2212 wants to merge 1 commit into
seetadev:mainfrom
Harshit-Mishra2212:fix/cohort-route-build-crash

Conversation

@Harshit-Mishra2212

Copy link
Copy Markdown

📌 Description

new MongoClient(uri) was called at module level in cohort/route.ts with a non-null assertion on process.env.MONGO_URI. During next build, Next.js evaluates route modules without runtime environment variables, so MONGO_URI is undefined at build time and MongoClient throws immediately crashing the entire build:

TypeError: Cannot read properties of undefined (reading 'startsWith')
at new MongoClient (mongodb/lib/mongo_client.js:52:61)
at app/api/cohort/route.js
Build error occurred: Failed to collect page data for /api/cohort

Reproducible on any clean clone without .env.local - exactly the environment CI pipelines and Vercel production builds run in. The ! non-null assertion only silences TypeScript, it does nothing at runtime.

Additionally, client.connect() was called on every GET request with no connection reuse, opening a new MongoDB connection per request and never closing it exhausting the Atlas connection pool under real load.

Not related to any specific issue but directly affects deployment reliability.


✅ Changes

  • Fix

  • Moved MongoClient creation into a getClient() helper that runs only at request time - build no longer crashes when MONGO_URI is absent

  • Added explicit MONGO_URI presence check that returns a meaningful error message instead of crashing with a TypeError

  • Added module-level cachedClient so the connected client is reused across requests - standard recommended pattern for MongoDB in Next.js serverless deployments


🔍 Additional Notes

No breaking changes. The GET handler behaviour is identical only the initialisation timing and connection reuse strategy changed. Existing callers of /api/cohort are unaffected.


Checklist

  • I have tested this code
  • I have added necessary documentation
  • I have linked relevant issue(s)
  • I followed the code style of the project
  • I reviewed my own code

@vercel

vercel Bot commented May 25, 2026

Copy link
Copy Markdown

@Harshit-Mishra2212 is attempting to deploy a commit to the SEETA's projects Team on Vercel.

A member of the Team first needs to authorize it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant