question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Preact will cause the mongodb package to not be found?

See original GitHub issue

Question 💬

When using nextjs with Preact the database part of auth will fail with -

https://next-auth.js.org/errors#oauth_callback_handler_error Error: no optional dependency [mongodb] defined in peerOptionalDependencies in any package.json
    at find_package_json_with_name (C:\Users\node_modules\require_optional\index.js:56:11)
    at require_optional (C:\Users\node_modules\require_optional\index.js:69:13)
    at Object.getAdapter (C:\Users\node_modules\@next-auth\typeorm-legacy-adapter\dist\index.js:104:55)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async Object.callback (C:\Users\.next\server\pages\api\auth\[...nextauth].js:5308:42)

I have tried to add the OptionalDependenciesand peerOptionalDependencies but both lead to the same error.

Is this a bug / Indented behaviour ? If so is there a way around it while still using preact? Removing pReact will fix this issue.

EDIT: Looking at previous PR’s seems like this is more of a bug, Here is extra details if required -

System:
    OS: Windows 10 10.0.19043
    CPU: (24) x64 AMD Ryzen 9 5900X 12-Core Processor
    Memory: 17.34 GB / 31.92 GB
  Binaries:
    Node: 14.17.2 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.10 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 7.21.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.1023.0), Chromium (92.0.902.84)
    Internet Explorer: 11.0.19041.906
  npmPackages:
    @preact/compat:  17.0.2
    next: ^11.1.0 => 11.1.0
    next-auth: ^3.29.0 => 3.29.0

How to reproduce ☕️

Sandbox - https://codesandbox.io/s/elated-rumple-yu39t

Contributing 🙌🏽

Yes, I am willing to help answer this question in a PR

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:27 (27 by maintainers)

github_iconTop GitHub Comments

2reactions
Patryks1commented, Aug 29, 2021

So I did test out our PR #2552 that rewrites the core to TypeScript (and also changes the build process quite a bit), and actually, it resolves the problem without more changes!

If you want to give it a try: next-auth@0.0.0-pr.2552.f73a37a5

Keep in mind, this is still a work in progress. When merged though, your issue here should be resolved.

If you don’t like to “live on the edge”, I suggest you wait a few days/weeks for us to get the new release over the finish line. 🙂 Hope that helps!

Im down to live on the edge for a while 😃, That PR does seem to fix the SessionProvider issue however it seems like the google provider does not work.

[...nextauth].js

import { MongoDBAdapter } from '@next-auth/mongodb-adapter';
import { MongoClient, ObjectId } from 'mongodb';
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

const client = new MongoClient('mongodb://127.0.0.1:27017');

export default NextAuth({
 providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    //TODO: Add Discord and Facebook
  ],
   session: {
     jwt: true,
     maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  debug: process.env.DEBUG_NEXTAUTH === 'true',
  secret: process.env.NEXT_SECRET,

  // TODO: TS interface in types.d.ts is incorrect for JWT options needs to be corrected. 
  jwt: {
    // openssl rand -base64 64
    secret: process.env.JWT_SECRET,
    // jose newkey -s 512 -t oct -a HS512
    signingKey: {
      kty: 'oct',
      kid: '',
      alg: 'HS512',
      k: '',
    },
    verificationOptions: {
      algorithms: ['HS256'],
    },
    encryption: true,
    // You can generate an encryption key by using `npx node-jose-tools newkey -s 256 -t oct -a A256GCM -u enc`
    encryptionKey: process.env.JWT_ENCRYPTION_KEY,
    decryptionKey: process.env.JWT_ENCRYPTION_KEY,
    decryptionOptions: {
      algorithms: ['A256GCM'],
    },
    adapter: MongoDBAdapter({
      db: () => client.db('db'),
      ObjectId,
    }),
});

Error

https://next-auth.js.org/errors#signin_oauth_error Unexpected token o in JSON at position 1 {
  error: {
    message: 'Unexpected token o in JSON at position 1',
    stack: 'SyntaxError: Unexpected token o in JSON at position 1\n' +
      '    at JSON.parse (<anonymous>)\n' +
      '    at Object.encode (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\.next\\server\\pages\\api\\auth\\[...nextauth].js:163:65)\n' +
      '    at createPKCE (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\.next\\server\\pages\\api\\auth\\[...nextauth].js:1977:43)\n' +
      '    at getAuthorizationUrl (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\.next\\server\\pages\\api\\auth\\[...nextauth].js:1623:52)\n' +
      '    at runMicrotasks (<anonymous>)\n' +
      '    at processTicksAndRejections (internal/process/task_queues.js:95:5)\n' +
      '    at async Object.signin (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\.next\\server\\pages\\api\\auth\\[...nextauth].js:3155:32)\n' +
      '    at async NextAuthHandler (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\.next\\server\\pages\\api\\auth\\[...nextauth].js:868:18)\n' +
      '    at async C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\.next\\server\\pages\\api\\auth\\[...nextauth].js:917:32\n' +
      '    at async Object.apiResolver (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\node_modules\\next\\dist\\server\\api-utils.js:101:9)\n' +
      '    at async DevServer.handleApiRequest (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\node_modules\\next\\dist\\server\\next-server.js:760:9)\n' +
      '    at async Object.fn (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\node_modules\\next\\dist\\server\\next-server.js:651:37)\n' +
      '    at async Router.execute (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\node_modules\\next\\dist\\server\\router.js:205:32)\n' +
      '    at async DevServer.run (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\node_modules\\next\\dist\\server\\next-server.js:825:29)\n' +
      '    at async DevServer.handleRequest (C:\\Users\\Pat\\Documents\\GitHub\\Pcific-Nextjs\\node_modules\\next\\dist\\server\\next-server.js:292:20)',
    name: 'SyntaxError'
  },
  provider: {
    id: 'google',
    name: 'Google',
    type: 'oauth',
    wellKnown: 'https://accounts.google.com/.well-known/openid-configuration',
    authorization: { params: [Object] },
    idToken: true,
    checks: [ 'pkce', 'state' ],
    profile: [Function: profile],
    signinUrl: 'http://localhost:3000/api/auth/signin/google',
    callbackUrl: 'http://localhost:3000/api/auth/callback/google',
    clientId: '',
    clientSecret: ''
  },
  message: 'Unexpected token o in JSON at position 1'
}

Sign in function

onClick={() =>
              signIn('google', {
                callbackUrl: `${window.location.origin}/`,
              })
            }
1reaction
balazsorban44commented, Sep 3, 2021

Awesome! Happy to accept a PR that I can check out locally. let’s open a different issue. Sounds like the original problem here is solved! 😊

Read more comments on GitHub >

github_iconTop Results From Across the Web

Troubleshooting — MongoDB Manual
These errors indicate that the MongoDB Public GPG key was not added in step Import the public key used by the package management...
Read more >
Installing mongoDB issue on ubuntu 20.01
The following packages have unmet dependencies: mongodb-org-database : Depends: mongodb-org-server but it is not going to be installed ...
Read more >
How to install mongodb from source code
I would like to know how to build mongodb with source code. ... Invalid MONGO_VERSION '', or could not derive from version.json or...
Read more >
Problems installing MongoDB on Ubuntu 20.04
Following the documentation for Mongo 4.4 on Ubuntu, I get the key, add the repository, then get the following error when running atp-get ......
Read more >
Error: couldn't connect to server 127.0.0.1:27017 - MongoDB
Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused ... NonExistentPath: Data directory /data/db not found., terminating
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found