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

FirebaseAdapter and Firebase giving "import" error #5551

Closed
bcthakre opened this issue Oct 11, 2022 · 38 comments · Fixed by #5945
Closed

FirebaseAdapter and Firebase giving "import" error #5551

bcthakre opened this issue Oct 11, 2022 · 38 comments · Fixed by #5945
Labels
adapters Changes related to the core code concerning database adapters bug Something isn't working firebase @auth/firebase-adapter

Comments

@bcthakre
Copy link

Adapter type

@next-auth/firebase-adapter

Environment

System Information.


System:
    OS: macOS 12.6
    CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
    Memory: 135.65 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.16.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 8.11.0 - /usr/local/bin/npm
  Browsers:
    Chrome: 105.0.5195.125
    Safari: 16.0
  npmPackages:
    next: 12.3.1 => 12.3.1 
    next-auth: ^4.13.0 => 4.13.0 
    react: 18.2.0 => 18.2.0 


  npmPackages:
    @next-auth/firebase-adapter: ^1.0.2 => 1.0.2 

Reproduction URL

https://github.com/bcthakre/nextjs-nextauth-2.git

Describe the issue

I am trying to use the FirebaseAdapter and Firestore to store user information for my NextJS app. However, getting the following error.


import { initializeApp } from "firebase/app";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.@next-auth/firebase-adapter (/Users/bt/Documents/nextjs/nextjs-nextauth-2/.next/server/pages/api/auth/[...nextauth].js:22:18)
    at __webpack_require__ (/Users/ct/Documents/nextjs/nextjs-nextauth-2/.next/server/webpack-api-runtime.js:33:42)

The issue was raised earlier but has not been fully resolved. Things I tried.

  1. Adding .mjs and .cjs to package-lock and next.config file.
  2. Removing and adding different firebase versions. From 9 to 11.

How to reproduce

Copy the github link as well.

[https://github.com/bcthakre/nextjs-nextauth-2.git]

Expected behavior

Should allow to store user and session information in Firestore. Also, need to provide a way to signIn and signOut

@bcthakre bcthakre added adapters Changes related to the core code concerning database adapters triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Oct 11, 2022
@github-actions github-actions bot added the firebase @auth/firebase-adapter label Oct 11, 2022
@mucahitdev
Copy link

i am getting the same error. did you solve it? @bcthakre

@bcthakre
Copy link
Author

Not yet @mucahitkok . Have asked on stackoverflow as well.

@balazsorban44 balazsorban44 added bug Something isn't working and removed triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Oct 12, 2022
@balazsorban44
Copy link
Member

balazsorban44 commented Oct 12, 2022

Looks like the latest release did not include the compiled version of the package

https://github.com/nextauthjs/next-auth/releases/tag/%40next-auth%2Ffirebase-adapter%40v1.0.2 🤔

https://github.com/nextauthjs/next-auth/actions/runs/3214540412/jobs/5255017831#step:6:101

The build was initiated but the output was still wrong.

reverting to 1.0.1 would be a temporary solution.

@bcthakre
Copy link
Author

bcthakre commented Oct 12, 2022

Thanks @balazsorban44 . Novice here. Shall I just revert back the next-auth to version 1.0.1

@nhuethmayr
Copy link

I highly advise not to use the current firebase adapter - for details please check out this link.
#5049

@bcthakre
Copy link
Author

Thanks @NorbertHuethmayr and @balazsorban44 . Solved the issue (seems like) by downgrading version.

@mucahitkok happy to share the solution

@Maximilian94
Copy link

Thanks @balazsorban44, downgrading to version 1.0.1 solved for me.

@bcthakre
Copy link
Author

@balazsorban44 Is there a specific guidance on how to change firestore security rules to add / view users with the adapter.

@RonAlmog
Copy link

having the same issue. patiently waiting for a fix, thank you ;)

@nhuethmayr
Copy link

You better look at this PR - maybe you can even upvote so that we get a bit more love from the maintainers.
#5628

@alpharaoh
Copy link

downgrading doesn't work for me 🥲

@RonAlmog
Copy link

@alpharaoh , what works for me right now is this: insall @next-auth/firebase-adapter@experinental,
and then go to your node_modules, next-auth/firebase-adapter, dist, and edit index.js
find: if(value.toDate)
add ? after the word value.
change to if(value?.toDate)
save and run, hope it will work for you.

@MalteBoehm
Copy link

Downgrading did not work on my end. Looking forward to a fix 🙃

@balazsorban44 balazsorban44 added good first issue Good issue to take for first time contributors and removed good first issue Good issue to take for first time contributors labels Oct 31, 2022
@yumartins
Copy link

Temporarily for this new version of firebase-adapter

In the project, use the next-transpile-modules lib

In version 13 of next we can use it inside next.config.js

experimental: {
    transpilePackages: [
      '@next-auth/firebase-adapter'
    ]
  }

@hsdonkin
Copy link

hsdonkin commented Nov 8, 2022

In the meantime I've had some luck by doing the following:

Here's what that code looks like:

import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';
// aliased import
import app from '@lib/firebase';

// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
export default NextAuth({
  // https://next-auth.js.org/providers
  providers: [
    CredentialsProvider({
      // The name to display on the sign in form (e.g. 'Sign in with...')
      name: 'Credentials',
      // The credentials is used to generate a suitable form on the sign in page.
      // You can specify whatever fields you are expecting to be submitted.
      // e.g. domain, username, password, 2FA token, etc.
      // You can pass any HTML attribute to the <input> tag through the object.
      credentials: {
        email: { label: 'Email', type: 'text', placeholder: 'jsmith' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials, req) {
        const { email, password } = credentials;
        try {
          const auth = getAuth(app);
          const userCredential = await signInWithEmailAndPassword(auth, email, password);
          // If no error and we have user data, return it
          if (userCredential?.user) {
            return userCredential?.user;
          }
        } catch (error) {
          console.log(error);
        }
        // Return null if user data could not be retrieved
        return null;
      },
    }),
  ],
});

Then in my app I can call signIn('credentials', { email, password, callbackUrl: '/' })

@bcthakre
Copy link
Author

bcthakre commented Nov 8, 2022

Thanks @hsdonkin . Can you please share the nextauth piece where you have used firestore adapter to connect to firebase for storing users. And what version of adapter you have used.

@hsdonkin
Copy link

This is my replacement for the adapter entirely, the authorize() function uses the firebase signin functions

@bcthakre
Copy link
Author

Let me give it a try this weekend.

@JorritWillaert
Copy link

I would like to use NextAuth with Firebase Authentication in my application, but I can't get around this issue.
@bcthakre have you found a solution or workaround?

Thanks!

@MalteBoehm
Copy link

I would like to use NextAuth with Firebase Authentication in my application, but I can't get around this issue.
@bcthakre have you found a solution or workaround?

Thanks!

Hey there, if you put this into your package.json it should work.

  "overrides": {
    "next-auth": {
      "next": "13.0.2"
    },
    "@next-auth/firebase-adapter": {
      "next": "13.0.2"
    }
  },

@EGT88
Copy link

EGT88 commented Nov 22, 2022

Temporarily for this new version of firebase-adapter

In the project, use the next-transpile-modules lib

In version 13 of next we can use it inside next.config.js

experimental: {
    transpilePackages: [
      '@next-auth/firebase-adapter'
    ]
  }

This sort of works but then later on shows error when declaring adapter below:

adapter: FirestoreAdapter({ db: db, ...firestoreFunctions, }),

TypeError: (0 , next_auth_firebase_adapter__WEBPACK_IMPORTED_MODULE_5_.default) is not a function

@Quelaan1
Copy link

I would like to use NextAuth with Firebase Authentication in my application, but I can't get around this issue. @bcthakre have you found a solution or workaround?

Thanks!

Use npm install next-auth @next-auth/firebase-adapter@experimental

@JorritWillaert
Copy link

next-auth @next-auth/firebase-adapter@experimental

Thank you for your answer!
I've tried this, with this in my [...nextauth].js file:

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { db } from "../../../firebase";
import { FirebaseAdapter } from "@next-auth/firebase-adapter";
import {
  collection,
  query,
  getDocs,
  where,
  limit,
  doc,
  getDoc,
  addDoc,
  updateDoc,
  deleteDoc,
  runTransaction,
} from "firebase/firestore";

export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  secret: process.env.NEXTAUTH_SECRET,
  adapter: FirebaseAdapter({
    db,
    collection,
    query,
    getDocs,
    where,
    limit,
    doc,
    getDoc,
    addDoc,
    updateDoc,
    deleteDoc,
    runTransaction,
  }),

  // The standard next auth page is this:
  // theme: {
  //   logo: "https://links.papareact.com/sq0",
  //   brandColor: "#f13287",
  //   colorScheme: "auto",
  // },
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {
    async session({ session, token, user }) {
      session.user.username = session.user.name
        .split(" ")
        .join("")
        .toLowerCase();
      session.user.uid = token.sub; // Google's user ID
      return session;
    },
  },
};
export default NextAuth(authOptions);

But then I get the following error:

https://next-auth.js.org/errors#adapter_error_getsessionanduser Missing or insufficient permissions. {
  message: 'Missing or insufficient permissions.',
  stack: 'FirebaseError: Missing or insufficient permissions.',
  name: 'FirebaseError'
}
[next-auth][error][SESSION_ERROR] 
https://next-auth.js.org/errors#session_error Missing or insufficient permissions. [FirebaseError: Missing or insufficient permissions.] {
  name: 'GetSessionAndUserError',
  code: 'permission-denied'
}

@bcthakre
Copy link
Author

bcthakre commented Nov 22, 2022 via email

@so-uvik
Copy link

so-uvik commented Nov 23, 2022

When i try to do this, import { FirebaseAdapter } from "@next-auth/firebase-adapter"; it gives me an error that says @next-Auth has no exported member FirebaseAdapter did you mean FirestoreAdapter? How do i fix this issue? I am using typescript for my project.

@Quelaan1
Copy link

When i try to do this, import { FirebaseAdapter } from "@next-auth/firebase-adapter"; it gives me an error that says @next-Auth has no exported member FirebaseAdapter did you mean FirestoreAdapter? How do i fix this issue? I am using typescript for my project.

FirebaseAdapter is not working currently, no matter what we try. Will have to wait for next update.

@Quelaan1
Copy link

I even tried previous versions.

@balazsorban44
Copy link
Member

Please refrain from calling out/mass tagging maintainers, it is not helpful for the discussion and only create hostility.

Do note that most of us work on this project in their free time and should be no expectations from anyone working more on it than what their life situation can support.

As several people pointed out earlier, downgrading did work #5551 (comment) so there was no imminent issue.

Furthermore, given this is a open source project with a very forgiving license, you can copy and paste the source code, create your fork, etc. if you are not satisfied with the maintenance.

I'm locking this thread to avoid being too heated, but please have another(?) look at our code of conduct https://github.com/nextauthjs/next-auth/blob/main/CODE_OF_CONDUCT.md before landing another comment like the above.

Thanks. 💚

@nextauthjs nextauthjs locked and limited conversation to collaborators Dec 3, 2022
@nextauthjs nextauthjs unlocked this conversation Dec 3, 2022
@balazsorban44
Copy link
Member

The fix is out in @next-auth/firebase-adapter@1.0.3

@bcthakre
Copy link
Author

bcthakre commented Dec 6, 2022

Thanks @balazsorban44 much appreciated. Will try this tonight

@bcthakre
Copy link
Author

bcthakre commented Dec 6, 2022

One quick question folks. Do we need to change security rules in the firestore rules. Any one has done it yet and want to share their insights

@so-uvik
Copy link

so-uvik commented Dec 8, 2022

import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { FirebaseAdapter } from "@next-auth/firebase-adapter";
import { db } from "../../../firebase"
import {
collection,
query,
getDocs,
where,
limit,
doc,
getDoc,
addDoc,
updateDoc,
deleteDoc,
runTransaction,
} from "firebase/firestore";

export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID!,
clientSecret: process.env.GOOGLE_SECRET_ID as string,
}),
],

adapter: FirebaseAdapter({
db,
collection,
query,
getDocs,
where,
limit,
doc,
getDoc,
addDoc,
updateDoc,
deleteDoc,
runTransaction,
})
,
callbacks: {
session({ session, token, user }) {
return session // The return type will match the one returned in useSession()
}
}
})

This is my code, but its still giving an error on line 3 that, nextauth has no exported member FirebaseAdapter did you mean FirestoreAdapter? I upgraded the package to firebase adapter@1.0.3 but the issue still persists. I am using firebase version 9.10.0 and typescript in my project. What am i doing wrong here?

@vedantmgoyal9
Copy link
Contributor

import { FirebaseAdapter } from "@next-auth/firebase-adapter"; to import { FirestoreAdapter } from "@next-auth/firebase-adapter";

@so-uvik
Copy link

so-uvik commented Dec 10, 2022

@vedantmgoyal2009 i did as you said it, changed adapter:FirebaseAdapter to adapter:FirestoreAdapter but it now highlights the next line i.e. "db" and throws the following error:

Argument of type '{ db: Firestore; collection: { (firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; (reference: CollectionReference<...>, path: string, ...pathSegments: string[]): CollectionReference<...>; (reference: DocumentReference<...>, path: string, ...pathSegments: string[]): Co...' is not assignable to parameter of type 'FirebaseOptions & FirestoreAdapterOptions'.
Object literal may only specify known properties, and 'db' does not exist in type 'FirebaseOptions & FirestoreAdapterOptions'.

What do i do now?

@so-uvik
Copy link

so-uvik commented Dec 13, 2022

[...nextauth].zip
Here is the file

@so-uvik
Copy link

so-uvik commented Dec 20, 2022

hey @vedantmgoyal2009 any updates?

@so-uvik
Copy link

so-uvik commented Jan 1, 2023

@so-uvik is the issue resolved?

No bro

@vedantmgoyal9
Copy link
Contributor

@so-uvik I'm no longer using next-auth, and also, major changes have been introduced. I hope you'll be able to find a solution on internet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
adapters Changes related to the core code concerning database adapters bug Something isn't working firebase @auth/firebase-adapter
Projects
None yet
Development

Successfully merging a pull request may close this issue.