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 { 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()),
});
Was this page helpful?