Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mongo Atlas - MongoServerSelectionError: getaddrinfo ENOTFOUND #833

Closed
1 task done
chechenev opened this issue Nov 5, 2020 · 41 comments
Closed
1 task done

Mongo Atlas - MongoServerSelectionError: getaddrinfo ENOTFOUND #833

chechenev opened this issue Nov 5, 2020 · 41 comments
Labels
question Ask how to do something or how something works

Comments

@chechenev
Copy link

chechenev commented Nov 5, 2020

Your question

What am I missing using Mongo Atlas?

What are you trying to do

  1. I'm trying to use Google auth
  2. Whitelisted all IPs on Mongo atlas
  3. Using env variable gives me: [next-auth][error][adapter_connection_error] MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.bixqg.mongodb.net
  4. I tried to do everything from similar issue Mongo atlas configuration #314 with no success
  5. I tried to deploy to vercel to run it not locally - the same result

Feedback
My code:

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

const options = {
    // Configure one or more authentication providers
    providers: [
        Providers.Google({
            clientId: process.env.GOOGLE_ID,
            clientSecret: process.env.GOOGLE_SECRET
        }),
    ],

    database: process.env.DATABASE_URL,
};

export default (req, res) => NextAuth(req, res, options)

The full error:

[next-auth][error][adapter_connection_error] MongoServerSelectionError: getaddrinfo ENOTFOUND cluster0.bixqg.mongodb.net
    at Timeout._onTimeout (/Users/maxim/WebstormProjects/tovarisch/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  name: 'MongoServerSelectionError',
  reason: TopologyDescription {
    type: 'Single',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map { 'cluster0.bixqg.mongodb.net:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
} 

[next-auth][error][oauth_callback_handler_error] TypeError: Cannot destructure property `manager` of 'undefined' or 'null'.

  • Found documentation but was incomplete
@chechenev chechenev added the question Ask how to do something or how something works label Nov 5, 2020
@SelvinM
Copy link

SelvinM commented Nov 6, 2020

I'm having the same problem, everything was working fine last week. I'm not sure why the connection stopped working all of the sudden.

@SelvinM
Copy link

SelvinM commented Nov 6, 2020

The issue seems to be related to typeorm version 0.2.29 according to this typeorm/typeorm#7009 .

Adding this to your package.json should fix the issue temporarily until they fix it "resolutions": { "typeorm": "0.2.28" }

Edit: I forgot to mention, this workaround only works if you are using yarn. Otherwise use @unflawed solution instead

@BskSmoothie
Copy link

Having same issue and adding "resolutions": { "typeorm": "0.2.28" } to my package.json didnt fix my problem. Any other ideas how to fix it?

@unflawed
Copy link

unflawed commented Nov 6, 2020

Having same issue and adding "resolutions": { "typeorm": "0.2.28" } to my package.json didnt fix my problem. Any other ideas how to fix it?

Fixed. If you get this, you need to install and import the reflect-metadata package.

  1. Install the npm package: npm install typeorm --save
  2. You need to install reflect-metadata shim: npm install reflect-metadata --save
  3. Import reflect-metadata somewhere in the global place of your app (for example in app.ts):
// _app.ts or _app.js
import "reflect-metadata";
...

Suggest making this clearer in the docs if possible.

@BskSmoothie
Copy link

Having same issue and adding "resolutions": { "typeorm": "0.2.28" } to my package.json didnt fix my problem. Any other ideas how to fix it?

Fixed. If you get this, you need to install and import the reflect-metadata package.

  1. Install the npm package: npm install typeorm --save
  2. You need to install reflect-metadata shim: npm install reflect-metadata --save
  3. Import reflect-metadata somewhere in the global place of your app (for example in app.ts):
// _app.ts or _app.js
import "reflect-metadata";
...

Suggest making this clearer in the docs if possible.

Worked for me. Thanks! 👍

@iaincollins
Copy link
Member

Thank you for the updates, linking to the outstanding issue and for a workaround (and confirming it works for you).

I'm going to keep an eye on the open issue with typeorm to see if we will should make a change to address or if it's an issue they plan to address upstream.

@jrista
Copy link

jrista commented Nov 7, 2020

I just switched from mLab to Mongo Atlas, and started having the same problem. I found this thread, and switched from "typeorm": "^0.2.29" to "typeorm": "0.2.28" (note the LACK of a caret ^ in the version, to LOCK it to 0.2.28). That seems to have resolved the issue, and I am now able to connect to Mongo Atlas.

If I switch back to 0.2.29 or use any kind of semantic version auto-upgrade option (^ or ~ or .x) in the version, it uses the latest, and also has a problem. Locking the typeorm node module version to 0.2.28 seems to resolve the issue.

@jrista
Copy link

jrista commented Nov 7, 2020

FWIW, before I changed the typeorm version down to 0.2.28, I did a bunch of testing elsewhere. All connection strings, mongodb:// and mongo+srv://, worked everywhere else I tested them. The mongo cli, Studio3T, Robo3T, using the node mongodb driver directly, etc.

@IRediTOTO
Copy link

Still error, I can't fix this...

@IRediTOTO
Copy link

Guys, did you fix it? @jrista
I am using this setup:
database: 'mongodb+srv://usn:pw@cluster-my-data.h215u.gcp.mongodb.net/myDB',
I'm sure this connect work because I am using next connect, now I want use next-auth....

@IRediTOTO
Copy link

fixed by this command npm i typeorm@0.2.28

@mapsam
Copy link

mapsam commented Nov 20, 2020

@unflawed your solution worked for me, thanks so much! ❤️

@rajat1saxena
Copy link

I had been struggling with this for last five hours or so. @BskSmoothie's solution solved it for me.

@Haple
Copy link

Haple commented Nov 22, 2020

I just switched from mLab to Mongo Atlas, and started having the same problem. I found this thread, and switched from "typeorm": "^0.2.29" to "typeorm": "0.2.28" (note the LACK of a caret ^ in the version, to LOCK it to 0.2.28). That seems to have resolved the issue, and I am now able to connect to Mongo Atlas.

If I switch back to 0.2.29 or use any kind of semantic version auto-upgrade option (^ or ~ or .x) in the version, it uses the latest, and also has a problem. Locking the typeorm node module version to 0.2.28 seems to resolve the issue.

Solved for me! Thanks @jrista :)

@dextermb
Copy link

@iaincollins Could you pin this issue so it's easier for other mongodb users to find? Thanks! 🎉

Adding the resolution to my package.json resolved the issue for me.

@jrista
Copy link

jrista commented Nov 23, 2020

@IRediTOTO I fixed it by falling back to 0.2.28. The issue seems to be with 0.2.29.

@andrewgwallace
Copy link

andrewgwallace commented Nov 23, 2020

@IRediTOTO I fixed it by falling back to 0.2.28. The issue seems to be with 0.2.29.

What does your database connection object look like as well as URL? Mongodb version? did you use npm or yarn?
I get the following error when using 0.2.28
[next-auth][error][adapter_connection_error] MongoParseError: Invalid connection string

@jrista
Copy link

jrista commented Nov 23, 2020

@andrewgwallace I am currently using a mongo:// connection string.

@andrewgwallace
Copy link

andrewgwallace commented Nov 25, 2020

To resolve for now without any "hackery", simply bypass the string parser's reliance on typeorm in the adapter and construct the object yourself. This way you don't have to install a previous typeorm version, modify your package.json, or include reflect-metadata.

If your string looks like this:
mongodb+srv://<username>:<password>@<cluster>.yu5ue.mongodb.net/<dbname>?retryWrites=true&w=majority

In your options for NextAuth, make your database value an object instead of a string. The structure should look as follows:

...
database: {
  type: "mongodb",
  uri: "mongodb+srv://<username>:<password>@<cluster>.yu5ue.mongodb.net/<dbname>",
  w: "majority",
  useNewUrlParser: true,
  useUnifiedTopology: true,
  retryWrites: true,
},

Important: Note that it says uri and not url.
Obviously it is recommended to store values in .env.local.

Optional values such as synchronize and logger can also be added to the object.

Source of the issue seems to be coming from typeorm config.
Big thanks to Richard Furberg for pointing me in the right direction.

@Furberg
Copy link

Furberg commented Nov 25, 2020

For whatever reason my comment got lost. Here it is again:

I got this as well while fooling around between two projects. The thing is that I only got it on one of them. The only difference was the connectionstring variable name in the .env.local file. Changing it from MONGODB_URI to DATABASE_URL (and updating all the references, rebuilding etc) made it work again. Not sure why, but worth a try.

@Furberg
Copy link

Furberg commented Nov 25, 2020

To resolve for now without any "hackery", simply bypass the string parser's reliance on typeorm in the adapter and construct the object yourself. This way you don't have to install a previous typeorm version, modify your package.json, or include reflect-metadata.

If your string looks like this:
mongodb+srv://<username>:<password>@<cluster>.yu5ue.mongodb.net/<dbname>?retryWrites=true&w=majority

In your options for NextAuth, make your database value an object instead of a string. The structure should look as follows:

...
database: {
  type: "mongodb",
  uri: "mongodb+srv://<username>:<password>@<cluster>.yu5ue.mongodb.net/<dbname>",
  w: "majority",
  useNewUrlParser: true,
  useUnifiedTopology: true,
  retryWrites: true,
},

Important: Note that it says uri and not url.
Obviously it is recommended to store values in .env.local.

Optional values such as synchronize and logger can also be added to the object.

Source of the issue seems to be coming from typeorm config.
Big thanks to Richard Furberg for pointing me in the right direction.

Worth mentioning is that I couldn't get the email configuration to work, until I changed it from a string to an object, just as you said about the connection string.

@jrista
Copy link

jrista commented Nov 25, 2020

@andrewgwallace Thank you for the update. Sounds like its due to parsing a full string url down into the various connection config parts then...

For my purposes, I don't actually need mongodb+srv. Not at this stage of the project, anyway. So falling back to a mongodb:// url worked ok for me. Good to know that I can use an object for config though.

@AnxiousDarkly
Copy link

not sure if I am the only one, but I haven't been able to get it working with any method in this thread so far.

@huksley
Copy link

huksley commented Nov 26, 2020

I have same problems and solution suggested by @andrewgwallace does not work for me :(

@unflawed
Copy link

@huksley have you tried this?
#833 (comment)

@huksley
Copy link

huksley commented Nov 26, 2020

@unflawed Yes, downgrading to typeorm 0.2.28 and following steps as you suggested #833 (comment) fixed problem connecting to MongoDB, thanks 👍

@AnxiousDarkly
Copy link

sorry I was wrong, setting a resolutions for typeorm was the only suggestion that worked.

@andrewgwallace
Copy link

andrewgwallace commented Nov 28, 2020

Yea -- my solution stopped working for me as well. 😭
I reverted to downgrading to typeorm 0.2.28 and the resolutions in my package.json. However now I'm getting
UnhandledPromiseRejectionWarning: Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
I've also tried the steps recommended in issue #552 of NextAuth. I've got a hunch the issue stems from #552 (comment) but that's out of the scope of my knowledge on how to resolve beyond what he suggested.

For now, the stability of NextAuth and MongoDB Atlas is not sufficient enough for production use IMO. I'll keep an eye on this and other tickets for progress.

Just going to note current key settings here where I last had it. If someone spots an issue let me know.
Node version: 12.19.0
package.json:

  "dependencies": {
     ...
    "next-auth": "^3.1.0",
    "reflect-metadata": "^0.1.13",
  },
  "optionalDependencies": {
    "mongodb": "^3.6.3"
  },
  "resolutions": {
    "typeorm": "0.2.28"
  },

_app.js
import "reflect-metadata";
[...nextauth].js

  database: {
    type: "mongodb",
    uri: process.env.DATABASE_URL, // mongodb+srv://<user>:<pass>@<cluster>.yu5ue.mongodb.net/<db>
    w: "majority",
    useNewUrlParser: true,
    useUnifiedTopology: true,
    retryWrites: true,
  },

@SelvinM
Copy link

SelvinM commented Nov 29, 2020

@andrewgwallace try changing "optionalDependencies" to "peerOptionalDependencies" in your package.json like so:
"peerOptionalDependencies": { "mongodb": "^3.6.2" }

@andrewgwallace
Copy link

andrewgwallace commented Nov 29, 2020

@andrewgwallace try changing "optionalDependencies" to "peerOptionalDependencies" in your package.json like so:
"peerOptionalDependencies": { "mongodb": "^3.6.2" }

Yes that seems to have resolved it! Thank you @SelvinM ! Had to install mongodb as a dependency of course.

@chechenev
Copy link
Author

I was able to fix it using the following config in [...nextauth].js:

 database: {
        type: "mongodb",
        useNewUrlParser: true,
        url: process.env.DATABASE_URL,
        ssl: true,
        useUnifiedTopology: true,
        authSource: "admin",
    },

@Diaa-Ghonim
Copy link

fixed thanks a lot .

npwxx added a commit to ListKeeper/ListKeeper that referenced this issue Dec 6, 2020
Pinned typeorm version to work around issue nextauthjs/next-auth#833
@imgregduh
Copy link
Contributor

This worked for me

// [...nextauth].js
database: process.env.DATABASE_URL,
// .env.local
DATABASE_URL=mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<db>

npm i typeorm@0.2.28

@Zertz
Copy link

Zertz commented Dec 27, 2020

Although it hasn't been released yet, the PR to fix this in TypeORM has been merged.

@matiastucci
Copy link

This worked for me:

yarn add typeorm@next

and adding this in the package.json:

"resolutions": {
  "typeorm": "0.3.0-alpha.24"
},

@YuriGor
Copy link
Contributor

YuriGor commented Jan 3, 2021

@matiastucci 's solution works for me with npm + npm-force-resolutions

@iaincollins
Copy link
Member

@Zertz @matiastucci Thanks for the update!

Great to know there is a fix in progress with TypeORM!

Will get that rolled in and we can update the dependencies and docs when typeorm@0.3.0 is out.

@pleerock
Copy link

Fix should be available in the latest typeorm @0.2.30

@balazsorban44
Copy link
Member

this is available in the latest canary release!

@jrista
Copy link

jrista commented Mar 30, 2021

We just updated to 0.2.31, then tried 0.2.30 as well...and we seem to have lost the ability to connect to an ObjectRocket Mongo DB with a normal mongo:// connection string. We connected to a local mongo fine, but the ObjectRocket is the service we use in all of our non-local environments. Not real sure what the issue is...it just seems to time out trying to connect.

@payzly-dev
Copy link

  1. npm i typeorm@0.2.28
  2. Remove carrot from the type orm version in your package.json file so that it looks like this: "typeorm": "0.2.28"
  3. Ensure you have the following in your package.json file:
"peerOptionalDependencies": {
    "mongodb": "^3.6.3"
  },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Ask how to do something or how something works
Projects
None yet
Development

Successfully merging a pull request may close this issue.