Skip to content

An adapter for Auth.js/NextAuth.js to allow you to connect to a MongoDB using Mongoose.

License

Notifications You must be signed in to change notification settings

brendon1555/authjs-mongoose-adapter

Repository files navigation


Mongoose Adapter - NextAuth.js / Auth.js

TypeScript npm Downloads GitHub Stars


Warning

This adapter cannot support Next.js middleware with next-auth until Mongoose supports the Next.js Edge Runtime. Or, Next.js adds Node.js net API support to middlewares. You CAN still generally use it with Next.js however.
See: Mongoose docs

Getting Started

  1. Install Auth.js (@auth/express, @auth/sveltekit, next-auth, etc.), mongoose and @brendon1555/authjs-mongoose-adapter:
npm install @brendon1555/authjs-mongoose-adapter mongoose @auth/express
  1. Add a MongoDB connection string to your environment variables:
MONGODB_URI=mongodb://localhost:27017/my-database
  1. Add this adapter to your auth config:

    1. Express
    import { ExpressAuth } from "@auth/express";
    import { MongooseAdapter } from "@brendon1555/authjs-mongoose-adapter";
    
    const app = express();
    
    app.use(
      "/auth/*",
      ExpressAuth({
        adapter: MongooseAdapter(process.env.MONGODB_URI),
        ...
      })
    );
    1. SvelteKit
    import { SvelteKitAuth } from "@auth/sveltekit";
    import { MongooseAdapter } from "@brendon1555/authjs-mongoose-adapter"
    
    export const { handle, signIn, signOut } = SvelteKitAuth({
      adapter: MongoDBAdapter(process.env.MONGODB_URI),
      ...
    });
    1. Next.js (Middleware not supported yet)
     import NextAuth from "next-auth"
     import { MongooseAdapter } from "@brendon1555/authjs-mongoose-adapter"
    
     export default NextAuth({
       adapter: MongooseAdapter(process.env.MONGODB_URI),
       ...
     })

License

ISC