{"success":true,"name":"reuse-one-mongoose-connection-in-next-js-cache-it-or-hot-rel","description":"Next.js project connecting to MongoDB inside API routes or server code","category":"ai-brimind","path":"ai-brimind/reuse-one-mongoose-connection-in-next-js-cache-it-or-hot-rel/SKILL.md","file":"SKILL.md","content":"---\nname: reuse-one-mongoose-connection-in-next-js-cache-it-or-hot-rel\ndescription: \"Next.js project connecting to MongoDB inside API routes or server code\"\n---\n\n# Reuse One Mongoose Connection in Next.js: Cache It, or Hot-Reload Will Multiply It\n\n## When to use\nProject is Next.js with MongoDB/Mongoose, and database connections are being opened inside API routes or handlers — or a plain mongoose.connect sits somewhere without the cached-connection pattern — so dev hot-reload and traffic spikes multiply connections.\n\n## Example request\nmongoose.connect called at the top of each API route file → in dev, every hot-reload and every request stacks new connections until MongoDB complains about the connection limit; the classic fix is one cached connection stored on the global object. Everything works for days, then 'too many connections' errors appear under load → each invocation opened its own pool instead of reusing one; connection reuse is THE serverless/Next.js gotcha with databases. A dbConnect() helper exists but some routes still import mongoose and query before awaiting it → intermittent 'buffering timed out' errors that vanish on retry; every DB touch must go through the same awaited helper. A long-running Express server calling connect once at startup → that pattern is fine THERE; the multiplication problem is specific to hot-reload and serverless-style execution, which is exactly what Next.js does.\n\n## Instructions\nAct as a Next.js backend developer who knows the framework's dirty secret about databases: your code does not run once like a classic server — dev mode hot-reloads modules constantly and serverless-style deployment may spin up many isolated instances — so a naive mongoose.connect does not create A connection, it creates a connection FACTORY with no off switch. Do this: (1) Establish the one blessed pattern: a single db.js/dbConnect module that caches the connection on the global object — check global.mongoose (or similar) first, return the existing connection or the in-flight connection PROMISE if one exists, and only call mongoose.connect when neither does. Caching the promise, not just the result, matters: it prevents the stampede where five parallel requests each start their own connect because none had finished yet. This exact pattern is the documented, standard solution for Mongoose-in-Next.js — copy the known-good shape rather than improvising it. (2) Route EVERYTHING through it: every API route, server action, or server component that touches a model starts with await dbConnect(); grep the codebase for any stray mongoose.connect or model query that can run before the helper — those strays are tomorrow's intermittent 'buffering timed out' ghost. (3) Read the connection string's pool settings consciously: the driver keeps a pool (default around 10 sockets per connection) — with one cached connection that is plenty for most apps; if you see connection counts exploding in MongoDB's metrics anyway, something is bypassing the cache, so trust the metric over the assumption and hunt the bypass. (4) Keep environment discipline attached: the URI comes from env config validated at startup, dev points at the dev database — the cached connection makes it extra important that it was aimed at the right world, because now EVERYTHING flows through it. (5) Verify like an operator: run dev, hot-reload a few times, hit several routes, then check the connection count in MongoDB (or Atlas metrics) — it should sit stable and small, not climb with every save of a file. Only call the setup done when the count stays flat under hot-reload and parallel requests, and every DB access path in the repo demonstrably passes through the single cached helper — 'it connects fine' is not the bar; 'it connects ONCE' is.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #220\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}