How to Connect MongoDB to a Next.js Application
Connect MongoDB to Next.js the right way: a cached client for hot reloads, server-only queries, serializable props, indexes, and a working notes app example.

Connecting MongoDB to Next.js takes five minutes to get working and much longer to get right. The classic failure is a connection that works locally, then floods the database with connections during development hot reloads or under serverless traffic in production. Connecting MongoDB to a Next.js application means creating a single reusable MongoDB client on the server, reading its connection string from an environment variable, and querying it from Server Components, Server Actions, or Route Handlers, never from the browser.
Quick Answer: Install the official mongodb driver, store your connection string in MONGODB_URI, create a lib/mongodb.ts module that caches one MongoClient promise on globalThis in development, and import it only in server code such as Server Components, Server Actions, and Route Handlers. Convert ObjectId values to strings before passing data to client components.
Where Should MongoDB Code Live in a Next.js App?
MongoDB code should live exclusively on the server. In the App Router, that means three places: Server Components for reading data while rendering a page, Server Actions for mutations triggered by forms or buttons, and Route Handlers for endpoints that external clients, webhooks, or mobile apps call. The database driver and your connection string must never be imported into a file marked "use client", because client bundles are downloaded by every visitor.
This server-first model is one of the main reasons teams choose a framework over a client-only app. If you are still deciding, our explanation of when Next.js beats a plain React SPA covers why direct server-side data access removes the need for a separate API layer in many projects.
A few terms are worth pinning down. The (a URI beginning with mongodb+srv:// for Atlas) contains the host, credentials, and options. The is the driver object that manages a pool of connections. A is a set of open connections the driver reuses across queries; creating a new client per request defeats it. is an optional object data modeling library that adds schemas and validation on top of the driver. You can use either; the connection caching principle is identical.



