Describe the bug
I keep getting Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json. It's so weird because I see it most of the time but no always. Sometimes I can sign in correctly and sometimes I get redirected to /api/auth/signin?error=Callback# and see this error in the client: Try signing with a different account. This is the full error log:
[GET] /api/auth/session
07:12:46:47
2020-08-06T05:12:46.563Z 044494dc-cf2a-4d4d-899c-a8209f59eec8 ERROR [next-auth][error][session_error] Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
at find_package_json_with_name (/var/task/node_modules/require_optional/index.js:56:11)
at require_optional (/var/task/node_modules/require_optional/index.js:69:13)
at Object.<anonymous> (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:118:53)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
at _next (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:30:194)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
https://next-auth.js.org/errors#session_error
To Reproduce
My code is in a private repo but if it's necessary I can try to create a new project and replicate it. My code is pretty standard. Just followed the docs. I only have 1 provider (Google) and I've already tried emptying the 3 collections (accounts, users and sessions)
Documentation feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.
Hi there! Hmm that's odd. It would be appreciate if you could share a link to a repo to replicate this issue.
I wonder if it's related to a custom webpack or babel config that is maybe doing something odd (or possibly a typo in an import statement somewhere?)
thanks for answering. Can I add you to the repo?
EDIT: at the time posting the link I tried it and asked a friend to try it too and we both were seeing the error. I just tried it again and don't see it 馃
I have the same issue:
2020-08-07T22:07:05.075Z 5079c22a-9a50-43bb-a19b-ea772c6ba6fd ERROR [next-auth][error][session_error] Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
at find_package_json_with_name (/var/task/node_modules/require_optional/index.js:56:11)
at require_optional (/var/task/node_modules/require_optional/index.js:69:13)
at Object.<anonymous> (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:118:53)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
at _next (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:30:194)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
https://next-auth.js.org/errors#session_error
I'm also experiencing the same issue:
2020-08-08T17:33:56.202Z 2d4d9902-78ef-4ee3-8b6f-5d0f87f02a46 ERROR [next-auth][error][session_error] Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
at find_package_json_with_name (/var/task/node_modules/require_optional/index.js:56:11)
at require_optional (/var/task/node_modules/require_optional/index.js:69:13)
at Object.<anonymous> (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:118:53)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
at _next (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:30:194)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
https://next-auth.js.org/errors#session_error
FYI, I didn't see this issue for 2 days and now I'm seeing it again. Didn't change any back end code though. But I noticed that 1 minute before seeing this error I got this one:
MongooseServerSelectionError: connection <monitor> to 127.0.0.1:27017 closed
at NativeConnection.Connection.openUri (/Users/mati/Development/annotations/node_modules/mongoose/lib/connection.js:827:32)
at Mongoose.connect (/Users/mati/Development/annotations/node_modules/mongoose/lib/index.js:335:15)
at dbConnect (webpack-internal:///./utils/dbConnect.js:12:68)
at handler (webpack-internal:///./pages/api/annotations/index.js:28:73)
at runMicrotasks (<anonymous>)
message: 'connection <monitor> to 127.0.0.1:27017 closed',
reason: TopologyDescription {
type: 'Single',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
not sure if it's related
Getting a new error now 馃槩 Still not touching any back end code. Same error in the logs (Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json)

Please share link to public repository or steps to replicate including versions (Nodejs, npm, etc.).
I have this error too
Getting a new error now 馃槩 Still not touching any back end code. Same error in the logs (
Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json)
I got this, let's see in the Warning https://next-auth.js.org/providers/google
I think I fixed it, just need delete package.lock and node modules then run npm i again
I cannot replicate this with the example project and am not seeing this issue on other projects.
If you are experiencing a problem please provide an example with steps to replicate.
I faced this issue also even if I removed mongodb and install it again the error will appears again
the solution which work for me as error hint appears
npm uninstall mongodb
to remove the mongodb
then
npm i mongodb --save-optional
it will appears on the package.json like that
{
"optionalDependencies": {
"mongodb": "^3.6.0"
}
}
FYI, I've removed useUnifiedTopology: true from my mongo connect options and so far so good.
unfortunately this works for some hours and the error back again
so this Not Working any more :(
{
"optionalDependencies": {
"mongodb": "^3.6.0"
}
}
with or without useUnifiedTopology: true still the problem show for me
I will try to downgrade mongodb and see what will happen
Yeah, I just got the error again after doing the optionalDependencies and useUnifiedTopology change 馃槩
I know it's not possible to get an answer without posting a project to reproduce it. I'm just posting this here for the rest of us having the same issue.
BTW, @alsemany how are you connecting to mongo?
I'm using the dbConnect example:
import mongoose from 'mongoose'
const connection = {}
async function dbConnect() {
if (connection.isConnected) {
return
}
const db = await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
// useUnifiedTopology: true,
useFindAndModify: false,
})
connection.isConnected = db.connections[0].readyState
}
export default dbConnect
For context, the error is from this line in the require_optional package:
https://github.com/christkv/require_optional/blob/master/index.js#L61
NextAuth.js uses this package to load MongoDB when a MongoDB database is specified, so it can load the ObjectID type.
The require_optional package is used by MongoDB driver itself to the same thing - which is why it replaced dynamic imports (which 2.x used) because quite a few folks had old / weird config setups that couldn't handle dynamic import statements yet.
Given three people who reported this have now cited a path of /var/task/node_modules/ I'm inclined to thing it's something that is going on with the build process and sounds like package.json is being removed as part of the build process (this will definitely break some libraries).
It's hard to say for sure without code to replicate this, but we might be at something of an impasse between people who can't use require_optional because of their build setup and people who can't use dynamic imports because for the same reason.
(I can think of a way to address it for both groups, but it would be a breaking change and one I would rather avoid.)
It would be interesting to know if /var/task/node_modules/next-auth contains a package.json file and what it contains, or if that is getting stripped for some reason.
Adding mongodb to peerOptionalDependencies in your own apps package.json might help, as long as it is bundled with the application:
"peerOptionalDependencies": {
"mongodb": "^3.6.0"
},
@matiastucci I'm using mongoose and I created all the models inside one folder so I just import any model inside the API
@iaincollins thanks for looking into this. I added mongo to peerOptionalDependencies. Hope that solves it 馃
Since I added mongo to peerOptionalDependencies I'm not seeing the error anymore. Thanks!
Just to add some search engine optimization to this issue, this error happens when deploying next-auth on Vercel and the solution @iaincollins posted seems to fix it!
My app is deployed on Vercel and I am getting the same error.
[GET] /api/auth/callback/google?state=4bdddef388295676496ad450cd70768b8e80fffb9e673f677854421050270146&code=4%2F0AY0e-g6v49ZSnhqkBJk0PqpY51e5ohcNqAhTEQNzjX86UvWmWwfRtAPsM78NYGB8fxjFOA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&prompt=none
15:36:32:68
2020-11-26T10:06:32.978Z 70fb4173-7ed1-4838-b4ae-6abc572134ee ERROR [next-auth][error][oauth_callback_handler_error] Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
at find_package_json_with_name (/var/task/node_modules/require_optional/index.js:56:11)
at require_optional (/var/task/node_modules/require_optional/index.js:69:13)
at Object.<anonymous> (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:118:53)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
at _next (/var/task/node_modules/next-auth/dist/adapters/typeorm/index.js:30:194)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
https://next-auth.js.org/errors#oauth_callback_handler_error
I had this issue today twice and will check if I can create an repo to reproduce it.
I'm getting this seemingly random as well. It starts happening, then nothing is working because of it for a few minutes. Then it disappears again, to come back a few hours later.
Most helpful comment
For context, the error is from this line in the
require_optionalpackage:https://github.com/christkv/require_optional/blob/master/index.js#L61
NextAuth.js uses this package to load MongoDB when a MongoDB database is specified, so it can load the ObjectID type.
The
require_optionalpackage is used by MongoDB driver itself to the same thing - which is why it replaced dynamic imports (which 2.x used) because quite a few folks had old / weird config setups that couldn't handle dynamic import statements yet.Given three people who reported this have now cited a path of
/var/task/node_modules/I'm inclined to thing it's something that is going on with the build process and sounds likepackage.jsonis being removed as part of the build process (this will definitely break some libraries).It's hard to say for sure without code to replicate this, but we might be at something of an impasse between people who can't use
require_optionalbecause of their build setup and people who can't use dynamic imports because for the same reason.(I can think of a way to address it for both groups, but it would be a breaking change and one I would rather avoid.)
It would be interesting to know if
/var/task/node_modules/next-authcontains apackage.jsonfile and what it contains, or if that is getting stripped for some reason.Adding
mongodbtopeerOptionalDependenciesin your own appspackage.jsonmight help, as long as it is bundled with the application: