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

Unable to use next-auth with provider: Error [ERR_PACKAGE_PATH_NOT_EXPORTED] #4143

Closed
imadarchid opened this issue May 11, 2023 · 18 comments · Fixed by #4153
Closed

Unable to use next-auth with provider: Error [ERR_PACKAGE_PATH_NOT_EXPORTED] #4143

imadarchid opened this issue May 11, 2023 · 18 comments · Fixed by #4153
Assignees
Labels
kind/bug Something isn't working status/done
Projects

Comments

@imadarchid
Copy link

What is the problem?

Hi there,

I am currently unable to configure a next-auth provider (EmailProvider) on blitz. I followed the configuration steps that are available in the docs (https://blitzjs.com/docs/next-auth), but this error occurs when I try to access the auth link (api/auth/email (or any other provider)/login).

The following error is what I keep getting: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './core/init' is not defined by "exports" in /Users/imadarchid/Desktop/Repositories/fire/node_modules/next-auth/package.json imported from /Users/imadarchid/Desktop/Repositories/fire/node_modules/@blitzjs/auth/dist/next-auth.cjs

Paste all your error logs here:

{
"stack": "Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './core/init' is not defined by \"exports\" in /Users/imadarchid/Desktop/Repositories/fire/node_modules/next-auth/package.json imported from /Users/imadarchid/Desktop/Repositories/fire/node_modules/@blitzjs/auth/dist/next-auth.cjs\n    at new NodeError (node:internal/errors:387:5)\n    at throwExportsNotFound (node:internal/modules/esm/resolve:365:9)\n    at packageExportsResolve (node:internal/modules/esm/resolve:649:3)\n    at packageResolve (node:internal/modules/esm/resolve:833:14)\n    at moduleResolve (node:internal/modules/esm/resolve:901:20)\n    at defaultResolve (node:internal/modules/esm/resolve:1115:11)\n    at nextResolve (node:internal/modules/esm/loader:163:28)\n    at ESMLoader.resolve (node:internal/modules/esm/loader:841:30)\n    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)\n    at ESMLoader.import (node:internal/modules/esm/loader:525:22)\n    at importModuleDynamically (node:internal/modules/cjs/loader:1129:29)\n    at importModuleDynamicallyWrapper (node:internal/vm/module:438:21)\n    at importModuleDynamically (node:vm:389:46)\n    at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)\n    at /Users/imadarchid/Desktop/Repositories/fire/node_modules/@blitzjs/auth/dist/next-auth.cjs:354:24\n    at Generator.next (<anonymous>)\n    at fulfilled (/Users/imadarchid/Desktop/Repositories/fire/node_modules/@blitzjs/auth/dist/next-auth.cjs:273:24)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)",
"message": "Package subpath './core/init' is not defined by \"exports\" in /Users/imadarchid/Desktop/Repositories/fire/node_modules/next-auth/package.json imported from /Users/imadarchid/Desktop/Repositories/fire/node_modules/@blitzjs/auth/dist/next-auth.cjs",
"code": "ERR_PACKAGE_PATH_NOT_EXPORTED"
}

Paste all relevant code snippets here:

// src/pages/api/auth[...nextauth].ts
import { api } from "src/blitz-server"
import EmailProvider from "next-auth/providers/email"
import { NextAuthAdapter, BlitzNextAuthOptions } from "@blitzjs/auth/next-auth"
import db, { User } from "db"
import { Role } from "types"

// Has to be defined separately for `profile` to be correctly typed below
const providers = [
  EmailProvider({
    from: process.env.GITHUB_CLIENT_ID as string,
    server: process.env.GITHUB_CLIENT_SECRET as string,
  }),
]

export default api(
  NextAuthAdapter({
    successRedirectUrl: "/",
    errorRedirectUrl: "/error",
    providers,
    callback: async (user, account, profile, session) => {
      console.log("USER SIDE PROFILE_DATA", { user, account, profile })
      let newUser: User
      try {
        newUser = await db.user.findFirstOrThrow({ where: { name: { equals: user.name } } })
      } catch (e) {
        newUser = await db.user.create({
          data: {
            email: user.email as string,
            name: user.name as string,
            role: "USER",
          },
        })
      }
      const publicData = {
        userId: newUser.id,
        role: newUser.role as Role,
        source: "email",
      }
      await session.$create(publicData)
      return { redirectUrl: "/" }
    },
  })
)
// blitz-server.ts
import { setupBlitzServer } from "@blitzjs/next"
import { AuthServerPlugin, PrismaStorage } from "@blitzjs/auth"
import { simpleRolesIsAuthorized } from "@blitzjs/auth"
import { BlitzLogger } from "blitz"
import db from "db"
import { authConfig } from "./blitz-client"

export const { gSSP, gSP, api, useAuthenticatedBlitzContext } = setupBlitzServer({
  plugins: [
    AuthServerPlugin({
      ...authConfig,
      storage: PrismaStorage(db),
      isAuthorized: simpleRolesIsAuthorized,
    }),
  ],
  logger: BlitzLogger({}),
})

// blitz-client.ts
import { AuthClientPlugin } from "@blitzjs/auth"
import { setupBlitzClient } from "@blitzjs/next"
import { BlitzRpcPlugin } from "@blitzjs/rpc"

export const authConfig = {
  cookiePrefix: "fire",
}

export const { withBlitz, BlitzProvider } = setupBlitzClient({
  plugins: [
    AuthClientPlugin({
      cookiePrefix: "web-cookie-prefix",
    }),
    BlitzRpcPlugin({}),
  ],
})

// next.config.js
const { withNextAuthAdapter } = require("@blitzjs/auth/next-auth")
const { withBlitz } = require("@blitzjs/next")

/**
 * @type {import('@blitzjs/next').BlitzConfig}
 **/
const config = {}

module.exports = withBlitz(withNextAuthAdapter(config))

What are detailed steps to reproduce this?

  1. Run a fresh instance of blitz
  2. Follow the steps on https://blitzjs.com/docs/next-auth
  3. Try to login via any provider

Run blitz -v and paste the output here:

Blitz version: 2.0.0-beta.27 (global)
Blitz version: 2.0.0-beta.27 (local)
macOS Ventura | darwin-arm64 | Node: v16.19.1


 Package manager: npm

  System:
    OS: macOS 13.3.1
    CPU: (10) arm64 Apple M2 Pro
    Memory: 933.28 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 16.19.1 - ~/.nvm/versions/node/v16.19.1/bin/node
    Yarn: Not Found
    npm: 8.19.3 - ~/.nvm/versions/node/v16.19.1/bin/npm
  npmPackages:
    @blitzjs/auth: 2.0.0-beta.27 => 2.0.0-beta.27 
    @blitzjs/next: 2.0.0-beta.27 => 2.0.0-beta.27 
    @blitzjs/rpc: 2.0.0-beta.27 => 2.0.0-beta.27 
    @prisma/client: 4.6.1 => 4.6.1 
    blitz: 2.0.0-beta.27 => 2.0.0-beta.27 
    next: ^13.3.0 => 13.4.1 
    prisma: 4.6.1 => 4.6.1 
    react: 18.2.0 => 18.2.0 
    react-dom: 18.2.0 => 18.2.0 
    typescript: ^4.8.4 => 4.9.5 

Please include below any other applicable logs and screenshots that show your problem:

No response

@imadarchid imadarchid added kind/bug Something isn't working status/triage labels May 11, 2023
@siddhsuresh
Copy link
Member

Hey @imadarchid, thanks for the issue. I am taking a look now. Would it be possible for you to provide a simple reproduction with a brand new app?

@imadarchid
Copy link
Author

Hi @siddhsuresh, thanks for your reply. Here's a repo based on a new blitz app.
Accessing http://localhost:3000/api/auth/email/login would yield the error.

@siddhsuresh
Copy link
Member

Thanks for the reproduction, I will take a look and let you know

@imadarchid
Copy link
Author

@siddhsuresh
I've been investigating for some time, and it seems like there are two main issues:

  1. AuthHandler: AuthHandler does not handle the case of using the EmailProvider. As you can see below, the function proceeds by calling getAuthorizationUrl from next-auth (next-auth/core/lib/oauth/authorization-url.js), which only handles the OAuth authorization flow. To handle the EmailProvider, we'd use the email() method that sits under next-auth/core/lib/email/signin.js.

  2. The error I have reported stems from missing exports on the next-auth library. Adding the following under exports on the package.json solves the error.

"exports": {
    ".": "./index.js",
    "./jwt": "./jwt/index.js",
    "./react": "./react/index.js",
    "./core": "./core/index.js",
    "./core/*": "./core/*.js", // new export 
    "./next": "./next/index.js",
    "./middleware": "./middleware.js",
    "./client/_utils": "./client/_utils.js",
    "./providers/*": "./providers/*.js"
  },

In addition, I suspect there are some inconsistencies in module systems between both libraries.
Is there something we can do about it from our end?

Anyway, I hope this is helpful. I am happy to open a PR to address the first point but would like to have your input on this first.

Thanks.

@siddhsuresh
Copy link
Member

siddhsuresh commented May 21, 2023

Hey @imadarchid, thanks for the time you spend on this. Yes, both your points are correct and making a patch with your mentioned package.json will make the adapter work in the mean time.

The purpose of making this adapter was to enhance the features of blitz-auth which already does email and traditional authenticated with the DX of the next auth OAuth providers.
Do you have a reason to use next auth email adapter over the scaffolded email auth?

I am in the process of making a PR for fixing the current adapter. Feel free to push a PR for the email adapter if it is a part of your requirement.

@siddhsuresh siddhsuresh added status/ready-to-work-on This issue is up for grabs and removed awaiting response labels May 21, 2023
@imadarchid
Copy link
Author

Thanks @siddhsuresh. I am mainly using NextAuth because I want to implement passwordless signin with magic links. The EmailProvider has a straightforward support for this.

@siddhsuresh
Copy link
Member

Thanks @siddhsuresh. I am mainly using NextAuth because I want to implement passwordless signin with magic links. The EmailProvider has a straightforward support for this.

@imadarchid Ah okay then, we should support the EmailProvider, are you willing to work on this?

@imadarchid
Copy link
Author

@siddhsuresh yes will try to spend some more time on this and open a PR when it's ready.

@sandheep45
Copy link

I am facing the same issue with google and facebook provider

Screenshot (68)
Screenshot (69)

@elsueno
Copy link

elsueno commented Sep 27, 2023

The problem is still present with Blitz 2.0.0-beta.33. Is there any solution in sight?

@tordans
Copy link
Contributor

tordans commented Oct 4, 2023

The problem is still present with Blitz 2.0.0-beta.33. Is there any solution in sight?

Feedback from @siddhsuresh from Discord @elsueno:

Will reopen this only for better context and continuity.
Easiest solution user side right now would be to patch next-auth packages.json to have the exports.
The only official approach go solve this is to remove the next Auth integration, add an authjs integration and get the r equired exports merged upstream, which is proving difficult for me to get the time, but is on my todo
More context: Web pack for some reason does not seem to accept the alias being setup so will have to take a look at fixing that.

Also Ping @siddhsuresh for reopening this issue.

@siddhsuresh siddhsuresh reopened this Oct 4, 2023
Toolkit automation moved this from Done to In progress Oct 4, 2023
@pzskyz
Copy link

pzskyz commented Oct 6, 2023

@elsueno The main problem is next-auth do not export core module in package.json. Try to add core export to next-auth package,json file in node_modules same as image below to make it work. This happened because file next-auth.cjs in @blitzjs/auth module import next-auth/core/init. I think we need to ask next-auth open a PR to export core module to fix this problem forever. One more thing in official docs is import withNextAuthAdapter from @blitzjs/auth not from @blitzjs/auth/next-auth.
image

@Aeolun
Copy link

Aeolun commented Oct 11, 2023

I've added the following "prepare" command to my scripts list, which will add the required exports every time install is called 🤷‍♂️

"prepare": "sed -i '34 i \"./core/*\": \"./core/*.js\",' node_modules/next-auth/package.json"

Obviously less than ideal, but it hopefully won't immediately break any time package.json changes.

@tordans
Copy link
Contributor

tordans commented Oct 24, 2023

The main problem is next-auth do not export core module in package.json. Try to add core export to next-auth package,json file in node_modules same as image below to make it work. This happened because file next-auth.cjs in @blitzjs/auth module import next-auth/core/init. I think we need to ask next-auth open a PR to export core module to fix this problem forever.

@pzskyz , @Aeolun, @siddhsuresh is there a ticket on this issue in the next-auth repo? I could not find any. I am not really clear on how to describe the issue properly, so chances are if one of you opened an issue it will sound more profound and is more likely taken seriously.

I think the first step would be to open a ticket before providing a PR so the community over there can comment on the topic from their point of view…

@msShanky
Copy link

msShanky commented Jan 14, 2024

Any solution for using next-auth with blitz ? this is still causing issues on "blitz": "2.0.2". This is stopping from using blitz for the projects with next auth required. Any updates would be truly appreciated.

@tordans
Copy link
Contributor

tordans commented Jan 14, 2024

@msShanky our current workaround is to patch the package. This turned out to be the better solution on different operating systems then the sed-workaround described above.

The nice thing about this is, once you update something you get a notice to update the patch.

@msShanky
Copy link

msShanky commented Jan 14, 2024

@tordans I did try the same but encountering issues with patch-pacakge first, it could not find any changes when I ran yarn patch-package next-auth so after digging I was able to make it work with this command yarn patch-package next-auth --exclude. Thanks a lot for the examples and this solved the error, you saved me from creating the project from scratch.

@flybayer flybayer closed this as not planned Won't fix, can't repro, duplicate, stale Feb 6, 2024
Toolkit automation moved this from In progress to Done Feb 6, 2024
@pzskyz
Copy link

pzskyz commented Jun 24, 2024

@msShanky Try for this patch file I used fo fix blitzjs-auth using for integrated for next-auth. Correct version you used in package.json and package-lock.json for two packages to apply patch. Patches only update correct version, any mistmatch will be ignore.

@blitzjs+auth+2.0.0-beta.33.patch
next-auth+4.24.6.patch
[...nextauth].ts.patch - This file original name is [...nextauth].ts in pages/api/auth/[...nextauth].ts I must replace extension name to github accepted upload. After patch with handle route trick make next-auth work like a charm with blitzjs-auth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/bug Something isn't working status/done
Projects
Development

Successfully merging a pull request may close this issue.

10 participants