Home > OS >  Firebase onAuthChanged returns the uid of the currently user but getIdToken() returns null?
Firebase onAuthChanged returns the uid of the currently user but getIdToken() returns null?

Time:04-19

[I am using next.js for this implementation]

I have this auth provider function:

const AuthContext = createContext({});

export function AuthProvider({ children }) {
  const [userCred, setUserCred] = useState()
  useEffect(() => {
    fetch('/api/userAuth').then(results => results.json()).then(data => setUserCred(data))
    
  }, [userCred]);
  return (
    <AuthContext.Provider value={{ userCred }}>{children}</AuthContext.Provider>
  );
}

export const useAuth = () =>useContext(AuthContext)

I've wrapped that provided into my main _app and it's working fine. The only problem is that getTokenId() always returns empty.

//in main app

import "../styles/globals.css";
import { AuthProvider } from "../context/AuthProvider";

function MyApp({ Component, pageProps }) {
  return (
    <AuthProvider>
      <Component {...pageProps} />
    </AuthProvider>
  );
}

export default MyApp;

However, when I immediately console.log the token from userCredential in my sign in function, the token is not empty.

 import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";

const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)     .then((userCredential) => { 
// Signed in 
const user = userCredential.user; 
token = userCredential._tokenResponse.idToken res.status(200).json({userId: user, token: token }); }) .catch((error) => { 
const errorCode = error.code; 
const errorMessage = error.message; res.status(401).json({errorCode: errorCode })
});

CodePudding user response:

as I see in the firebase user credentials, there are two methods for getting token

getIdTokenResult(
      forceRefresh?: boolean
    ): Promise<firebase.auth.IdTokenResult>;
    /**
     * Returns a JSON Web Token (JWT) used to identify the user to a Firebase
     * service.
     *
     * Returns the current token if it has not expired. Otherwise, this will
     * refresh the token and return a new one.
     *
     * @param forceRefresh Force refresh regardless of token
     *     expiration.
     */
    getIdToken(forceRefresh?: boolean): Promise<string>;

So you can use these methods, for example.

const token = userCredential.getIdToken();

OR

const token = userCredential.getIdTokenResult();

Also, It always returns a promise, so make sure that you take a result of the promise. Thanks )

  • Related