Configuring NextAuth with Custom User Data

NextAuth.js is a powerful authentication library for Next.js applications. When integrating it with Firebase, you might encounter issues where not all user data is available in the session object after authentication. This guide will help you configure NextAuth to ensure that all necessary user data is included in the session.

Setting Up NextAuth

To get started, you need to create an API route for NextAuth. This is typically done in the pages/api/auth/[...nextauth].js file. Below is an example configuration:

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { login } from './your-login-function'; // Import your login function

export default (req, res) => {
  NextAuth(req, res, {
    providers: [
      Providers.Credentials({
        name: 'Credentials',
        credentials: {
          phone: { label: 'Phone number', type: 'text' },
          password: { label: 'Password', type: 'password' },
        },
        authorize: async (credentials) => {
          const { phone, password } = credentials;
          const response = await login(phone, password);

          // Check if login was successful
          if (response.status === 200) {
            const user = {
              phone,
              ...response.data.info,
            };
            console.log('User data from Firestore:', user);
            return Promise.resolve(user);
          } else {
            return Promise.resolve(null); // Invalid credentials
          }
        },
      }),
    ],
    callbacks: {
      session: async (session, user) => {
        console.log('User data during session callback:', user);
        // Attach additional user data to the session
        session.user.phone = user.phone;
        session.user.id = user.id;
        session.user.surname = user.surname;
        return Promise.resolve(session);
      },
    },
    debug: false,
  });
};

Explanation of the Code

  • Providers: We use the Credentials provider to authenticate users with their phone number and password.
  • Authorize Callback: This function checks the credentials against your Firebase backend. If successful, it constructs a user object containing all relevant data.
  • Session Callback: This is where we customize the session object. By default, NextAuth only includes a minimal set of user information (like name and email). Here, we extend the session object to include additional user data such as phone number and surname.

Using the Session in Your Components

To access the session data in your React components, use the useSession hook from NextAuth:

import { useSession } from 'next-auth/react';

const MyComponent = () => {
  const { data: session, status } = useSession();

  if (status === 'loading') {
    return <p>Loading...</p>;
  }

  if (session) {
    return <p>Signed in as {session.user.email} (Phone: {session.user.phone})</p>;
  }

  return <a href="/api/auth/signin">Sign in</a>;
};

Conclusion

By following this configuration, you can ensure that all necessary user data from Firebase Firestore is included in the session object after authentication. This allows you to access additional user information seamlessly throughout your Next.js application.