1aa341f635
## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Errors have helpful link attached, see `contributing.md` ## Feature - [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. - [ ] Errors have helpful link attached, see `contributing.md` ## Documentation / Examples - [ ] Make sure the linting passes by running `pnpm lint` - [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
33 lines
1 KiB
TypeScript
33 lines
1 KiB
TypeScript
import { MongoClient } from 'mongodb'
|
|
|
|
if (!process.env.MONGODB_URI) {
|
|
throw new Error('Invalid environment variable: "MONGODB_URI"')
|
|
}
|
|
|
|
const uri = process.env.MONGODB_URI
|
|
const options = {}
|
|
|
|
let client
|
|
let clientPromise: Promise<MongoClient>
|
|
|
|
if (!process.env.MONGODB_URI) {
|
|
throw new Error('Please add your Mongo URI to .env.local')
|
|
}
|
|
|
|
if (process.env.NODE_ENV === 'development') {
|
|
// In development mode, use a global variable so that the value
|
|
// is preserved across module reloads caused by HMR (Hot Module Replacement).
|
|
if (!global._mongoClientPromise) {
|
|
client = new MongoClient(uri, options)
|
|
global._mongoClientPromise = client.connect()
|
|
}
|
|
clientPromise = global._mongoClientPromise
|
|
} else {
|
|
// In production mode, it's best to not use a global variable.
|
|
client = new MongoClient(uri, options)
|
|
clientPromise = client.connect()
|
|
}
|
|
|
|
// Export a module-scoped MongoClient promise. By doing this in a
|
|
// separate module, the client can be shared across functions.
|
|
export default clientPromise
|