Next.js Discord

Discord Forum

Firebase and NextAuth v5 in Next.js 14.0

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
Hi all - I'm currently working on integrating Firebase authentication with NextAuth v5 in a Next.js 14.0 application, following the Adding Authentication guide (https://nextjs.org/learn/dashboard-app/adding-authentication). However, I'm encountering difficulties in getting Firebase to work alongside NextAuth for user authentication and session management.

I can log the user in on the server, however the client is not updated, so I when access information on the user (i.e. refreshed auth tokens), it is not available. When i access auth.currentUser I get null

LoginForm.tsx
'use client'
const LoginForm = () => {
  // ...
  const handleLogin = async (event: React.FormEvent) => {
    event.preventDefault();
    try {
      const formData = new FormData();
      formData.append('email', email);
      formData.append('password', password);
      await signInAction(undefined, formData);
    } catch (error) {
      //...
    }
  };
  // ...
};

NextAuth (/auth.ts):
export const { auth, signIn, signOut } = NextAuth({
  providers: [
    Credentials({
      async authorize(credentials) {
        // ...
        if (parsedCredentials.success) {
          const { email, password } = parsedCredentials.data;
          const user = await firebaseSignIn(email, password);
          if (!user) return null;
          return user;
        }
        console.log('Invalid credentials');
        return null;
      },
    }),
  ],
  pages: {
    signIn: '/authentication/login',
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      try {
        const isLoggedIn = !!auth?.user
        const isOnAuthPages = nextUrl.pathname.startsWith('/authentication')
        if (!isOnAuthPages) {
          if (isLoggedIn) {
            return true
          }
          return false
        } else if (isLoggedIn) {
          return NextResponse.redirect(new URL('/', nextUrl))
        }
        return true
      } catch (error) {
        //...
      }
    }
});

1 Reply

Siamese
hi @Polar bear , have you find any solution ? i'm facing the same issue and I'm wondering how to keep the JWT in the session and how to refresh it when it has expired ?