1

I am building a web application with NextJS 13, Firebase, and NextAuth. I am using a custom AuthProvider component with a createContext hook to manage user authentication. However, I am facing an issue where the user is being created twice in the database.

Here is a simplified version of my AuthProvider code:

"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import {
  collection,
  getDocs,
  query,
  where,
  serverTimestamp,
  addDoc,
} from "firebase/firestore";
import { db } from "@/lib/firebaseConfig";

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const { data: session } = useSession();

  const getUser = async (email) => {
    const q = query(collection(db, "users"), where("email", "==", email));
    const querySnapshot = await getDocs(q);
    const user = [];
    querySnapshot.forEach((doc) => {
      user.push({ ...doc.data(), id: doc.id });
    });
    return user[0];
  };

  const createUser = async (email) => {
    const user = {
      email: session.user.email,
      name: session.user.name,
      image: session.user.image,
      createdAt: serverTimestamp(),
    };
    const docRef = await addDoc(collection(db, "users"), user);
    return { ...user, id: docRef.id };
  };

  useEffect(() => {
    if (session) {
      getUser(session.user.email).then((user) => {
        if (user) {
          setUser(user);
          setLoading(false);
        } else {
          createUser(session.user.email).then((user) => {
            setUser(user);
            setLoading(false);
          });
        }
      });
    } else {
      setLoading(false);
    }
  }, [session]);

  return (
    <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
  );
};

I have noticed that whenever a user logs in for the first time, the createUser function is called twice, resulting in two user records being created in the database.

I have tried adding a check for the existence of the user before calling the createUser function, but this did not solve the issue. I suspect that the useEffect hook is causing the createUser function to be called twice, but I am not sure how to fix this.

Can anyone help me understand why the user is being created twice and how to fix this issue? Thank you in advance.

EDIT: editing next.config.js to

const nextConfig = {
  reactStrictMode: false,
};

and restarting my app works, but it's not ideal as it affects other parts of my project.

0 Answers0