better auth not work well with mongodb, it uses collection user but mongodb uses users both are different #2587

Closed
opened 2026-03-13 10:05:04 -05:00 by GiteaMirror · 9 comments
Owner

Originally created by @akashmahlaz on GitHub (Dec 22, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

it uses user collection but mongodb uses users collection which is very bad and it is not stable as autjjs

Current vs. Expected behavior

the user coloction by default should users so both mongodb and better auth and session not conflict

What version of Better Auth are you using?

latest most latest

System info

it is database issue also it is not working well with nextjs tornopach 16

Which area(s) are affected? (Select all that apply)

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
});

Additional context

please check or replace

Originally created by @akashmahlaz on GitHub (Dec 22, 2025). ### Is this suited for github? - [ ] Yes, this is suited for github ### To Reproduce it uses user collection but mongodb uses users collection which is very bad and it is not stable as autjjs ### Current vs. Expected behavior the user coloction by default should users so both mongodb and better auth and session not conflict ### What version of Better Auth are you using? latest most latest ### System info ```bash it is database issue also it is not working well with nextjs tornopach 16 ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, }); ``` ### Additional context please check or replace
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 22, 2025):

The issue you're facing appears to be related to the default naming convention conflicts between Better Auth and MongoDB's user collection. Better Auth may be hardcoded to look for a collection named "user" instead of the plural "users," which is the default in MongoDB.

To address this, you can either modify your collection name in MongoDB to "user" or adjust the Better Auth configuration to accommodate the "users" naming convention. Unfortunately, there doesn't seem to be a direct fix in the current version as per the available documentation.

You could also check existing open issues or submit a new one to Better Auth's repository detailing your use case for further assistance from the team. For now, consider tagging Beka (@bekacru) or Max (@ping__) for their input on resolving this conflict, as they may have more insight about potential updates or workarounds.

What other issues or features would you like to explore with Better Auth?

If you need more help, tag @better-auth-agent in a comment so I can respond.

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Dec 22, 2025): The issue you're facing appears to be related to the default naming convention conflicts between Better Auth and MongoDB's user collection. Better Auth may be hardcoded to look for a collection named "user" instead of the plural "users," which is the default in MongoDB. To address this, you can either modify your collection name in MongoDB to "user" or adjust the Better Auth configuration to accommodate the "users" naming convention. Unfortunately, there doesn't seem to be a direct fix in the current version as per the available documentation. You could also check existing open issues or submit a new one to Better Auth's repository detailing your use case for further assistance from the team. For now, consider tagging Beka (@bekacru) or Max (@ping__) for their input on resolving this conflict, as they may have more insight about potential updates or workarounds. What other issues or features would you like to explore with Better Auth? _If you need more help, tag @better-auth-agent in a comment so I can respond._ <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@dosubot[bot] commented on GitHub (Dec 22, 2025):

Hi @akashmahlaz! I'm Dosu and I’m helping the better-auth team.

Better Auth uses "user" as the default MongoDB collection name, but you can configure it to use "users" (or any other name) to match your existing collections and avoid conflicts. To do this, set the user model name in your config:

import { betterAuth } from "better-auth"
import { mongodbAdapter } from "better-auth/adapters/mongodb"
import { MongoClient } from "mongodb"

const client = new MongoClient(process.env.MONGODB_URI!)
const db = client.db()

export const auth = betterAuth({
  database: mongodbAdapter(db, { client }),
  user: { modelName: "users" }, // <-- use "users" collection
  emailAndPassword: { enabled: true },
})

Alternatively, you can enable the usePlural option in the MongoDB adapter config to pluralize all collection names automatically:

database: mongodbAdapter(db, { client, usePlural: true }),

This issue happens because Better Auth does not pluralize collection names by default, unlike Mongoose or Auth.js. If you have an existing "users" collection, you must explicitly set the model name or enable pluralization to avoid conflicts and ensure compatibility with other libraries or your own schemas [source 1] [source 2].

If you still experience instability or session issues with Next.js (especially with Turbopack), make sure you initialize the MongoDB adapter with both the database and the MongoClient instance as shown above—this is required for stable session handling in serverless environments [source].

Let me know if you need a config example for a different setup or more details on session stability!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

@dosubot[bot] commented on GitHub (Dec 22, 2025): <!-- Greeting --> Hi @akashmahlaz! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> Better Auth uses "user" as the default MongoDB collection name, but you can configure it to use "users" (or any other name) to match your existing collections and avoid conflicts. To do this, set the user model name in your config: ```typescript import { betterAuth } from "better-auth" import { mongodbAdapter } from "better-auth/adapters/mongodb" import { MongoClient } from "mongodb" const client = new MongoClient(process.env.MONGODB_URI!) const db = client.db() export const auth = betterAuth({ database: mongodbAdapter(db, { client }), user: { modelName: "users" }, // <-- use "users" collection emailAndPassword: { enabled: true }, }) ``` Alternatively, you can enable the `usePlural` option in the MongoDB adapter config to pluralize all collection names automatically: ```typescript database: mongodbAdapter(db, { client, usePlural: true }), ``` This issue happens because Better Auth does not pluralize collection names by default, unlike Mongoose or Auth.js. If you have an existing "users" collection, you must explicitly set the model name or enable pluralization to avoid conflicts and ensure compatibility with other libraries or your own schemas [[source 1]](https://github.com/better-auth/better-auth/issues/177) [[source 2]](https://github.com/better-auth/better-auth/issues/1908). If you still experience instability or session issues with Next.js (especially with Turbopack), make sure you initialize the MongoDB adapter with both the database and the MongoClient instance as shown above—this is required for stable session handling in serverless environments [[source]](https://github.com/better-auth/better-auth/issues/4802). Let me know if you need a config example for a different setup or more details on session stability! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/e08cb767-a2a3-4ef4-9f56-d6aff8bc9835?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=Better%20Auth%20uses%20%22user%22%20as%20the%20default%20MongoDB%20collection%20name%2C%20but%20you%20can%20configure%20it%20to%20use%20%22users%22%20%28or%20any%20other%20name%29%20to%20match%20your%20existing%20collections%20and%20avoid%20conflicts.%20To%20do%20this%2C%20set%20the%20user%20model%20name%20in%20your%20config%3A%0A%0A%60%60%60typescript%0Aimport%20%7B%20betterAuth%20%7D%20from%20%22better-auth%22%0Aimport%20%7B%20mongodbAdapter%20%7D%20from%20%22better-auth/adapters/mongodb%22%0Aimport%20%7B%20MongoClient%20%7D%20from%20%22mongodb%22%0A%0Aconst%20client%20%3D%20new%20MongoClient%28process.env.MONGODB_URI%21%29%0Aconst%20db%20%3D%20client.db%28%29%0A%0Aexport%20const%20auth%20%3D%20betterAuth%28%7B%0A%20%20database%3A%20mongodbAdapter%28db%2C%20%7B%20client%20%7D%29%2C%0A%20%20user%3A%20%7B%20modelName%3A%20%22users%22%20%7D%2C%20//%20%3C--%20use%20%22users%22%20collection%0A%20%20emailAndPassword%3A%20%7B%20enabled%3A%20true%20%7D%2C%0A%7D%29%0A%60%60%60%0A%0AAlternatively%2C%20you%20can%20enable%20the%20%60usePlural%60%20option%20in%20the%20MongoDB%20adapter%20config%20to%20pluralize%20all%20collection%20names%20automatically%3A%0A%0A%60%60%60typescript%0Adatabase%3A%20mongodbAdapter%28db%2C%20%7B%20client%2C%20usePlural%3A%20true%20%7D%29%2C%0A%60%60%60%0A%0AThis%20issue%20happens%20because%20Better%20Auth%20does%20not%20pluralize%20collection%20names%20by%20default%2C%20unlike%20Mongoose%20or%20Auth.js.%20If%20you%20have%20an%20existing%20%22users%22%20collection%2C%20you%20must%20explicitly%20set%20the%20model%20name%20or%20enable%20pluralization%20to%20avoid%20conflicts%20and%20ensure%20compatibility%20with%20other%20libraries%20or%20your%20own%20schemas%20%5B%5Bsource%201%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/177%29%20%5B%5Bsource%202%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/1908%29.%0A%0AIf%20you%20still%20experience%20instability%20or%20session%20issues%20with%20Next.js%20%28especially%20with%20Turbopack%29%2C%20make%20sure%20you%20initialize%20the%20MongoDB%20adapter%20with%20both%20the%20database%20and%20the%20MongoClient%20instance%20as%20shown%20above%E2%80%94this%20is%20required%20for%20stable%20session%20handling%20in%20serverless%20environments%20%5B%5Bsource%5D%5D%28https%3A//github.com/better-auth/better-auth/issues/4802%29.%0A%0ALet%20me%20know%20if%20you%20need%20a%20config%20example%20for%20a%20different%20setup%20or%20more%20details%20on%20session%20stability%21)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/6928)
Author
Owner

@akashmahlaz commented on GitHub (Dec 22, 2025):

tell me how to setup file by file all code

@akashmahlaz commented on GitHub (Dec 22, 2025): tell me how to setup file by file all code
Author
Owner

@akashmahlaz commented on GitHub (Dec 22, 2025):

tell me how to setup file by file all code

@dosu

@akashmahlaz commented on GitHub (Dec 22, 2025): tell me how to setup file by file all code @dosu
Author
Owner

@akashmahlaz commented on GitHub (Dec 22, 2025):

@better-auth-agent tell me how to setup file by file all code

@akashmahlaz commented on GitHub (Dec 22, 2025): @better-auth-agent tell me how to setup file by file all code
Author
Owner

@better-auth-agent[bot] commented on GitHub (Dec 22, 2025):

To set up Better Auth in a file-by-file manner, follow these steps:

  1. Install the Package:
    Use npm or another package manager to install Better Auth:

    npm install better-auth
    
  2. Set Environment Variables:
    Create a .env file in your project root and add the following:

    BETTER_AUTH_SECRET=<your_secret_key>
    BETTER_AUTH_URL=http://localhost:3000  # Update as needed
    
  3. Create the Auth Instance:
    Create a file named auth.ts in a suitable directory (like src/lib/). In this file, set up your Better Auth instance:

    import { betterAuth } from "better-auth";
    
    export const auth = betterAuth({
        // Add your configurations here
        emailAndPassword: {
            enabled: true,
        },
        // If using a database (e.g., MongoDB), ensure correct collection names
    });
    
  4. Configure the Database:
    If you're using a database, configure it within auth.ts. For example:

    // MongoDB connection
    import { MongoClient } from 'mongodb';
    
    const client = new MongoClient('<your_mongo_uri>');
    const database = client.db('your_database');
    
    export const auth = betterAuth({
        database: {
            client,  // Pass the MongoClient instance
            collection: 'users',  // Ensure this matches your MongoDB collection name
        },
        // other configurations...
    });
    
  5. Migrate Your Data:
    If migrating from an existing setup, ensure user data is correctly mapped to prevent conflicts between your application and MongoDB collections.

  6. Initialize and Run:
    Ensure your project is configured to start the server (e.g., with Next.js) and handle any initialization for the auth instance.

If you run into conflicts with collection names or other issues, consider checking the configuration and adjusting your database settings. Feel free to ask if you need further help or specific details about any of the steps! Would you like more information on database configurations?

DiagramDiscordGitHub

Diagram Join Star

@better-auth-agent[bot] commented on GitHub (Dec 22, 2025): To set up Better Auth in a file-by-file manner, follow these steps: 1. **Install the Package**: Use npm or another package manager to install Better Auth: ```bash npm install better-auth ``` 2. **Set Environment Variables**: Create a `.env` file in your project root and add the following: ```plaintext BETTER_AUTH_SECRET=<your_secret_key> BETTER_AUTH_URL=http://localhost:3000 # Update as needed ``` 3. **Create the Auth Instance**: Create a file named `auth.ts` in a suitable directory (like `src/lib/`). In this file, set up your Better Auth instance: ```typescript import { betterAuth } from "better-auth"; export const auth = betterAuth({ // Add your configurations here emailAndPassword: { enabled: true, }, // If using a database (e.g., MongoDB), ensure correct collection names }); ``` 4. **Configure the Database**: If you're using a database, configure it within `auth.ts`. For example: ```typescript // MongoDB connection import { MongoClient } from 'mongodb'; const client = new MongoClient('<your_mongo_uri>'); const database = client.db('your_database'); export const auth = betterAuth({ database: { client, // Pass the MongoClient instance collection: 'users', // Ensure this matches your MongoDB collection name }, // other configurations... }); ``` 5. **Migrate Your Data**: If migrating from an existing setup, ensure user data is correctly mapped to prevent conflicts between your application and MongoDB collections. 6. **Initialize and Run**: Ensure your project is configured to start the server (e.g., with Next.js) and handle any initialization for the auth instance. If you run into conflicts with collection names or other issues, consider checking the configuration and adjusting your database settings. Feel free to ask if you need further help or specific details about any of the steps! Would you like more information on database configurations? <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) • [Discord](https://discord.gg/fG2XXEuQX3) • [GitHub](https://github.com/Skyvern-AI/Skyvern) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/skyvern_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/fG2XXEuQX3) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/Skyvern-AI/Skyvern)
Author
Owner

@dosubot[bot] commented on GitHub (Dec 22, 2025):

Here’s a file-by-file setup guide for Better Auth with MongoDB in a Next.js project, using the "users" collection and ensuring session stability (works for Next.js 16/Turbopack) [docs]:


1. .env

Create this in your project root:

BETTER_AUTH_SECRET=your-very-long-random-secret-key
BETTER_AUTH_URL=http://localhost:3000
MONGODB_URI=mongodb://localhost:27017/your-db-name
  • Use a strong secret (32+ chars).
  • Set your actual MongoDB URI and database name.

2. lib/auth.ts

Configure Better Auth to use the "users" collection and stable MongoDB adapter [docs]:

import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI!);
await client.connect();
const db = client.db();

export const auth = betterAuth({
  baseURL: process.env.BETTER_AUTH_URL,
  secret: process.env.BETTER_AUTH_SECRET,
  database: mongodbAdapter(db, { client }), // Pass both db and client for session stability
  user: { modelName: "users" }, // Use "users" collection
  emailAndPassword: { enabled: true },
  // Optional: session config for expiration, cookie cache, etc.
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
    updateAge: 60 * 60 * 24,     // 1 day
    cookieCache: { enabled: true, maxAge: 5 * 60 },
  },
  // Optional: plugins for Next.js server actions
  plugins: [
    require("better-auth/next-js").nextCookies(),
  ],
});
  • If you want MongoDB to generate ObjectIds, add:
    advanced: { database: { generateId: false } }
    
    [source]

3. API Route

For App Router (app/api/auth/[...all]/route.ts):

import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { GET, POST } = toNextJsHandler(auth);

[docs]

For Pages Router (pages/api/auth/[...all].ts):

import { auth } from "@/lib/auth";
import { toNodeHandler } from "better-auth/node";

export const config = { api: { bodyParser: false } };
export default toNodeHandler(auth.handler);

4. proxy.ts (Next.js 16+ route protection)

Protect routes by checking for a session cookie [demo]:

import { getSessionCookie } from "better-auth/cookies";
import { NextRequest, NextResponse } from "next/server";

export async function proxy(request: NextRequest) {
  const sessionCookie = getSessionCookie(request);
  if (!sessionCookie) {
    return NextResponse.redirect(new URL("/sign-in", request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard"], // Protect /dashboard route
};

5. lib/auth-client.ts (Frontend client)

Create a Better Auth client for your frontend [docs]:

import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL || "http://localhost:3000",
});

  • Backend must allow credentials and include your frontend origin in trustedOrigins.
  • Frontend API requests (e.g., axios) must use withCredentials: true so cookies are sent [source].
  • For HTTPS, set cookie attributes to secure: true and sameSite: "none".

7. MongoDB Driver Version

  • Use MongoDB driver v6.x (e.g., 6.21.0). v7 is not officially supported and may cause errors [source].

Let me know if you need frontend form examples or want to customize fields/session logic further!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other

Chat with Dosu Open in Cursor Join Discord Share on X

@dosubot[bot] commented on GitHub (Dec 22, 2025): <!-- Answer --> Here’s a file-by-file setup guide for Better Auth with MongoDB in a Next.js project, using the "users" collection and ensuring session stability (works for Next.js 16/Turbopack) [[docs](https://github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/installation.mdx#L13-L519)]: --- ### 1. `.env` Create this in your project root: ```env BETTER_AUTH_SECRET=your-very-long-random-secret-key BETTER_AUTH_URL=http://localhost:3000 MONGODB_URI=mongodb://localhost:27017/your-db-name ``` - Use a strong secret (32+ chars). - Set your actual MongoDB URI and database name. --- ### 2. `lib/auth.ts` Configure Better Auth to use the "users" collection and stable MongoDB adapter [[docs](https://github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/adapters/mongo.mdx#L14-L48)]: ```typescript import { betterAuth } from "better-auth"; import { mongodbAdapter } from "better-auth/adapters/mongodb"; import { MongoClient } from "mongodb"; const client = new MongoClient(process.env.MONGODB_URI!); await client.connect(); const db = client.db(); export const auth = betterAuth({ baseURL: process.env.BETTER_AUTH_URL, secret: process.env.BETTER_AUTH_SECRET, database: mongodbAdapter(db, { client }), // Pass both db and client for session stability user: { modelName: "users" }, // Use "users" collection emailAndPassword: { enabled: true }, // Optional: session config for expiration, cookie cache, etc. session: { expiresIn: 60 * 60 * 24 * 7, // 7 days updateAge: 60 * 60 * 24, // 1 day cookieCache: { enabled: true, maxAge: 5 * 60 }, }, // Optional: plugins for Next.js server actions plugins: [ require("better-auth/next-js").nextCookies(), ], }); ``` - If you want MongoDB to generate ObjectIds, add: ```typescript advanced: { database: { generateId: false } } ``` [[source](https://github.com/better-auth/better-auth/issues/4741)] --- ### 3. API Route #### For App Router (`app/api/auth/[...all]/route.ts`): ```typescript import { auth } from "@/lib/auth"; import { toNextJsHandler } from "better-auth/next-js"; export const { GET, POST } = toNextJsHandler(auth); ``` [[docs](https://github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/integrations/next.mdx#L12-L393)] #### For Pages Router (`pages/api/auth/[...all].ts`): ```typescript import { auth } from "@/lib/auth"; import { toNodeHandler } from "better-auth/node"; export const config = { api: { bodyParser: false } }; export default toNodeHandler(auth.handler); ``` --- ### 4. `proxy.ts` (Next.js 16+ route protection) Protect routes by checking for a session cookie [[demo](https://github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/demo/nextjs/proxy.ts#L1-L15)]: ```typescript import { getSessionCookie } from "better-auth/cookies"; import { NextRequest, NextResponse } from "next/server"; export async function proxy(request: NextRequest) { const sessionCookie = getSessionCookie(request); if (!sessionCookie) { return NextResponse.redirect(new URL("/sign-in", request.url)); } return NextResponse.next(); } export const config = { matcher: ["/dashboard"], // Protect /dashboard route }; ``` --- ### 5. `lib/auth-client.ts` (Frontend client) Create a Better Auth client for your frontend [[docs](https://github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/integrations/next.mdx#L12-L393)]: ```typescript import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL || "http://localhost:3000", }); ``` --- ### 6. CORS & Cookie Notes - Backend must allow credentials and include your frontend origin in trustedOrigins. - Frontend API requests (e.g., axios) must use `withCredentials: true` so cookies are sent [[source](https://github.com/better-auth/better-auth/issues/5705#issuecomment-3474162632)]. - For HTTPS, set cookie attributes to `secure: true` and `sameSite: "none"`. --- ### 7. MongoDB Driver Version - Use MongoDB driver v6.x (e.g., 6.21.0). v7 is not officially supported and may cause errors [[source](https://github.com/better-auth/better-auth/issues/6812)]. --- Let me know if you need frontend form examples or want to customize fields/session logic further! <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/b990204a-aa6d-4935-989f-7c3b5942c2e0?feedback_type=other)</sup> [![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Open in Cursor](https://dosu.dev/dosu-in-cursor.svg)](https://cursor.com/link/prompt?text=Here%E2%80%99s%20a%20file-by-file%20setup%20guide%20for%20Better%20Auth%20with%20MongoDB%20in%20a%20Next.js%20project%2C%20using%20the%20%22users%22%20collection%20and%20ensuring%20session%20stability%20%28works%20for%20Next.js%2016/Turbopack%29%20%5B%5Bdocs%5D%28https%3A//github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/installation.mdx%23L13-L519%29%5D%3A%0A%0A---%0A%0A%23%23%23%201.%20%60.env%60%0A%0ACreate%20this%20in%20your%20project%20root%3A%0A%0A%60%60%60env%0ABETTER_AUTH_SECRET%3Dyour-very-long-random-secret-key%0ABETTER_AUTH_URL%3Dhttp%3A//localhost%3A3000%0AMONGODB_URI%3Dmongodb%3A//localhost%3A27017/your-db-name%0A%60%60%60%0A-%20Use%20a%20strong%20secret%20%2832%2B%20chars%29.%20%20%0A-%20Set%20your%20actual%20MongoDB%20URI%20and%20database%20name.%0A%0A---%0A%0A%23%23%23%202.%20%60lib/auth.ts%60%0A%0AConfigure%20Better%20Auth%20to%20use%20the%20%22users%22%20collection%20and%20stable%20MongoDB%20adapter%20%5B%5Bdocs%5D%28https%3A//github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/adapters/mongo.mdx%23L14-L48%29%5D%3A%0A%0A%60%60%60typescript%0Aimport%20%7B%20betterAuth%20%7D%20from%20%22better-auth%22%3B%0Aimport%20%7B%20mongodbAdapter%20%7D%20from%20%22better-auth/adapters/mongodb%22%3B%0Aimport%20%7B%20MongoClient%20%7D%20from%20%22mongodb%22%3B%0A%0Aconst%20client%20%3D%20new%20MongoClient%28process.env.MONGODB_URI%21%29%3B%0Aawait%20client.connect%28%29%3B%0Aconst%20db%20%3D%20client.db%28%29%3B%0A%0Aexport%20const%20auth%20%3D%20betterAuth%28%7B%0A%20%20baseURL%3A%20process.env.BETTER_AUTH_URL%2C%0A%20%20secret%3A%20process.env.BETTER_AUTH_SECRET%2C%0A%20%20database%3A%20mongodbAdapter%28db%2C%20%7B%20client%20%7D%29%2C%20//%20Pass%20both%20db%20and%20client%20for%20session%20stability%0A%20%20user%3A%20%7B%20modelName%3A%20%22users%22%20%7D%2C%20//%20Use%20%22users%22%20collection%0A%20%20emailAndPassword%3A%20%7B%20enabled%3A%20true%20%7D%2C%0A%20%20//%20Optional%3A%20session%20config%20for%20expiration%2C%20cookie%20cache%2C%20etc.%0A%20%20session%3A%20%7B%0A%20%20%20%20expiresIn%3A%2060%20%2A%2060%20%2A%2024%20%2A%207%2C%20//%207%20days%0A%20%20%20%20updateAge%3A%2060%20%2A%2060%20%2A%2024%2C%20%20%20%20%20//%201%20day%0A%20%20%20%20cookieCache%3A%20%7B%20enabled%3A%20true%2C%20maxAge%3A%205%20%2A%2060%20%7D%2C%0A%20%20%7D%2C%0A%20%20//%20Optional%3A%20plugins%20for%20Next.js%20server%20actions%0A%20%20plugins%3A%20%5B%0A%20%20%20%20require%28%22better-auth/next-js%22%29.nextCookies%28%29%2C%0A%20%20%5D%2C%0A%7D%29%3B%0A%60%60%60%0A-%20If%20you%20want%20MongoDB%20to%20generate%20ObjectIds%2C%20add%3A%0A%20%20%60%60%60typescript%0A%20%20advanced%3A%20%7B%20database%3A%20%7B%20generateId%3A%20false%20%7D%20%7D%0A%20%20%60%60%60%0A%20%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/4741%29%5D%0A%0A---%0A%0A%23%23%23%203.%20API%20Route%0A%0A%23%23%23%23%20For%20App%20Router%20%28%60app/api/auth/%5B...all%5D/route.ts%60%29%3A%0A%0A%60%60%60typescript%0Aimport%20%7B%20auth%20%7D%20from%20%22%40/lib/auth%22%3B%0Aimport%20%7B%20toNextJsHandler%20%7D%20from%20%22better-auth/next-js%22%3B%0A%0Aexport%20const%20%7B%20GET%2C%20POST%20%7D%20%3D%20toNextJsHandler%28auth%29%3B%0A%60%60%60%0A%5B%5Bdocs%5D%28https%3A//github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/integrations/next.mdx%23L12-L393%29%5D%0A%0A%23%23%23%23%20For%20Pages%20Router%20%28%60pages/api/auth/%5B...all%5D.ts%60%29%3A%0A%0A%60%60%60typescript%0Aimport%20%7B%20auth%20%7D%20from%20%22%40/lib/auth%22%3B%0Aimport%20%7B%20toNodeHandler%20%7D%20from%20%22better-auth/node%22%3B%0A%0Aexport%20const%20config%20%3D%20%7B%20api%3A%20%7B%20bodyParser%3A%20false%20%7D%20%7D%3B%0Aexport%20default%20toNodeHandler%28auth.handler%29%3B%0A%60%60%60%0A%0A---%0A%0A%23%23%23%204.%20%60proxy.ts%60%20%28Next.js%2016%2B%20route%20protection%29%0A%0AProtect%20routes%20by%20checking%20for%20a%20session%20cookie%20%5B%5Bdemo%5D%28https%3A//github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/demo/nextjs/proxy.ts%23L1-L15%29%5D%3A%0A%0A%60%60%60typescript%0Aimport%20%7B%20getSessionCookie%20%7D%20from%20%22better-auth/cookies%22%3B%0Aimport%20%7B%20NextRequest%2C%20NextResponse%20%7D%20from%20%22next/server%22%3B%0A%0Aexport%20async%20function%20proxy%28request%3A%20NextRequest%29%20%7B%0A%20%20const%20sessionCookie%20%3D%20getSessionCookie%28request%29%3B%0A%20%20if%20%28%21sessionCookie%29%20%7B%0A%20%20%20%20return%20NextResponse.redirect%28new%20URL%28%22/sign-in%22%2C%20request.url%29%29%3B%0A%20%20%7D%0A%20%20return%20NextResponse.next%28%29%3B%0A%7D%0A%0Aexport%20const%20config%20%3D%20%7B%0A%20%20matcher%3A%20%5B%22/dashboard%22%5D%2C%20//%20Protect%20/dashboard%20route%0A%7D%3B%0A%60%60%60%0A%0A---%0A%0A%23%23%23%205.%20%60lib/auth-client.ts%60%20%28Frontend%20client%29%0A%0ACreate%20a%20Better%20Auth%20client%20for%20your%20frontend%20%5B%5Bdocs%5D%28https%3A//github.com/better-auth/better-auth/blob/35072dd59f19b50147fd39202b17a2c2cf26a164/docs/content/docs/integrations/next.mdx%23L12-L393%29%5D%3A%0A%0A%60%60%60typescript%0Aimport%20%7B%20createAuthClient%20%7D%20from%20%22better-auth/react%22%3B%0A%0Aexport%20const%20authClient%20%3D%20createAuthClient%28%7B%0A%20%20baseURL%3A%20process.env.NEXT_PUBLIC_BETTER_AUTH_URL%20%7C%7C%20%22http%3A//localhost%3A3000%22%2C%0A%7D%29%3B%0A%60%60%60%0A%0A---%0A%0A%23%23%23%206.%20CORS%20%26%20Cookie%20Notes%0A%0A-%20Backend%20must%20allow%20credentials%20and%20include%20your%20frontend%20origin%20in%20trustedOrigins.%0A-%20Frontend%20API%20requests%20%28e.g.%2C%20axios%29%20must%20use%20%60withCredentials%3A%20true%60%20so%20cookies%20are%20sent%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/5705%23issuecomment-3474162632%29%5D.%0A-%20For%20HTTPS%2C%20set%20cookie%20attributes%20to%20%60secure%3A%20true%60%20and%20%60sameSite%3A%20%22none%22%60.%0A%0A---%0A%0A%23%23%23%207.%20MongoDB%20Driver%20Version%0A%0A-%20Use%20MongoDB%20driver%20v6.x%20%28e.g.%2C%206.21.0%29.%20v7%20is%20not%20officially%20supported%20and%20may%20cause%20errors%20%5B%5Bsource%5D%28https%3A//github.com/better-auth/better-auth/issues/6812%29%5D.%0A%0A---%0A%0ALet%20me%20know%20if%20you%20need%20frontend%20form%20examples%20or%20want%20to%20customize%20fields/session%20logic%20further%21)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/6928)
Author
Owner

@bytaesu commented on GitHub (Dec 22, 2025):

Hello @akashmahlaz,

If you set it up this way https://www.better-auth.com/docs/adapters/mongo, MongoDB will create collections as shown below. I wasn't able to reproduce this issue when I tried.

Image
@bytaesu commented on GitHub (Dec 22, 2025): Hello @akashmahlaz, If you set it up this way https://www.better-auth.com/docs/adapters/mongo, MongoDB will create collections as shown below. I wasn't able to reproduce this issue when I tried. <img width="302" height="151" alt="Image" src="https://github.com/user-attachments/assets/d0cdee65-6aa1-4e69-b403-f40b64f30f0a" />
Author
Owner

@bytaesu commented on GitHub (Dec 22, 2025):

This doesn’t seem to be an actual issue, so I’ll close it. Feel free to mention me or reopen if the issue persists.

@bytaesu commented on GitHub (Dec 22, 2025): This doesn’t seem to be an actual issue, so I’ll close it. Feel free to mention me or reopen if the issue persists.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#2587