Danli Denny Deng
Danli Denny Deng

Reputation: 391

TypeError: Cannot read properties of undefined (reading 'db') with next-auth

https://www.youtube.com/watch?v=H4ptrFimcSM&list=PLC3y8-rFHvwgC9mj0qv972IO5DmD-H0ZH&index=76

I am learning next-auth in nextjs by watching this youtube video. in the [...nextauth].js file,

import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'

import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from "mongodb"

export default NextAuth({
  
  adapter: MongoDBAdapter(clientPromise),

  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    }),
  ],
  
  database: process.env.DB_URL,
  
  session: {
    jwt: true
  },
  jwt: {
    secret: 'randomofonvaifiamloao',
  }
})

then I got above error, please help!

Upvotes: 2

Views: 5134

Answers (1)

Danli Denny Deng
Danli Denny Deng

Reputation: 391

In [...nextauth].js

import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'

import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from "./lib/mongodb"

export default NextAuth({
  
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    }),
  ],
  
  adapter: MongoDBAdapter(clientPromise),

})

In mongodb.js

import { MongoClient } from "mongodb"

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

let client
let clientPromise

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

Upvotes: 1

Related Questions