MongoDB Client: Connected or Not connected

Hello. I am using better-auth for the first time. I am using MongoDB as my database. Now, my questions is, should I pass a connected MongoDB client or just a normal MongoClient, and better-auth will do the connection itself? Here is my current code. It works so far. (Kindly ignore the Property 'db' does not exist on type '{ success: true; client: MongoClient; } | { success: false; } error mongodbAdapter(client.db()) I am in the midst of a refactor'.
import { MongoClient } from 'mongodb';
import logger from '@/logger';

export default async function getMongoDbClient(): Promise<
{ success: true; client: MongoClient } | { success: false }
> {
// Creates a new MongoDB client, connects to it and returns it
const mongoClient = new MongoClient(process.env.MONGODB_URI as string);
logger.info('Created new MongoClient instance.');

try {
await mongoClient.connect();
logger.info('Connected to the newly created MongoDB client!');
} catch {
logger.error('Failed to connect to MongoDB.');
return { success: false };
}

logger.info('Returning newly created & connected MongoDB client.');

return { success: true, client: mongoClient };
}
import { MongoClient } from 'mongodb';
import logger from '@/logger';

export default async function getMongoDbClient(): Promise<
{ success: true; client: MongoClient } | { success: false }
> {
// Creates a new MongoDB client, connects to it and returns it
const mongoClient = new MongoClient(process.env.MONGODB_URI as string);
logger.info('Created new MongoClient instance.');

try {
await mongoClient.connect();
logger.info('Connected to the newly created MongoDB client!');
} catch {
logger.error('Failed to connect to MongoDB.');
return { success: false };
}

logger.info('Returning newly created & connected MongoDB client.');

return { success: true, client: mongoClient };
}
import { betterAuth } from 'better-auth';
import { mongodbAdapter } from 'better-auth/adapters/mongodb';
import { nextCookies } from 'better-auth/next-js';
import getMongoDbClient from './db';

const client = await getMongoDbClient();

export const auth = betterAuth({
emailAndPassword: {
enabled: true,
},

socialProviders: {
google: {
prompt: 'select_account',
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},

plugins: [nextCookies()],

database: mongodbAdapter(client.db()),
});
import { betterAuth } from 'better-auth';
import { mongodbAdapter } from 'better-auth/adapters/mongodb';
import { nextCookies } from 'better-auth/next-js';
import getMongoDbClient from './db';

const client = await getMongoDbClient();

export const auth = betterAuth({
emailAndPassword: {
enabled: true,
},

socialProviders: {
google: {
prompt: 'select_account',
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},

plugins: [nextCookies()],

database: mongodbAdapter(client.db()),
});
5 Replies
The Untraceable
The Untraceable2mo ago
i do const db = client.db("auth"), and pass it to mongodbAdapter
Shayokh
ShayokhOP2mo ago
Umm does you client.db("auth") return a connected MongoClient?
The Untraceable
The Untraceable2mo ago
// lib/db.ts
import { MongoClient } from 'mongodb';

if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI;
const options = {};

let client: MongoClient;

if (process.env.NODE_ENV === 'development') {
const globalWithMongo = global as typeof globalThis & {
_mongoClient?: MongoClient;
};

if (!globalWithMongo._mongoClient) {
globalWithMongo._mongoClient = new MongoClient(uri, options);
}
client = globalWithMongo._mongoClient;
} else {
client = new MongoClient(uri, options);
}

export { client };
// lib/db.ts
import { MongoClient } from 'mongodb';

if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI;
const options = {};

let client: MongoClient;

if (process.env.NODE_ENV === 'development') {
const globalWithMongo = global as typeof globalThis & {
_mongoClient?: MongoClient;
};

if (!globalWithMongo._mongoClient) {
globalWithMongo._mongoClient = new MongoClient(uri, options);
}
client = globalWithMongo._mongoClient;
} else {
client = new MongoClient(uri, options);
}

export { client };
// auth.ts
import { client } from '@/lib/db';

const db = client.db('auth');
// auth.ts
import { client } from '@/lib/db';

const db = client.db('auth');
I am using NextJS too
Shayokh
ShayokhOP2mo ago
Damn Nice Singleton pattern Is this MongoDB singleton working in production well?
The Untraceable
The Untraceable2mo ago
Yea its from nextjs docs iirc

Did you find this page helpful?