You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase邮箱验证异常:user为null无法发送验证邮件求助

Fixing "user is null" Error & Enforcing Email Verification in Firebase

Hey there! I see exactly what's causing your issues—let's fix them one by one.

1. Why you're getting "user is null"

The createUserWithEmailAndPassword() method runs asynchronously. When you immediately call firebase.auth().currentUser right after it, the user creation process hasn't finished yet, so currentUser is still null. You need to wait for the promise to resolve before accessing the user object.

2. Fixing the Sign-Up & Verification Code

Here's the corrected sign-up handler that properly waits for the user to be created before sending the verification email:

// Add create user event
btnSignUp.addEventListener('click', e => {
  // Get email and password
  const email = txtEmail.value;
  const pass = txtPassword.value;
  const auth = firebase.auth();

  // Wait for the user creation promise to resolve
  auth.createUserWithEmailAndPassword(email, pass)
    .then(userCredential => {
      // Now we have access to the user object via userCredential.user
      const user = userCredential.user;
      // Send verification email
      return user.sendEmailVerification();
    })
    .then(() => {
      console.log("Verification email sent!");
      // Optional: Redirect to a "check your email" page here
    })
    .catch(e => console.log(e.message));
});

3. Fixing the Auth State Listener (Enforce Verification)

Your current listener has a couple of issues: it doesn't check if user exists first, and the order of window.location and signOut might cause unexpected behavior. Here's the improved version:

// Add a realtime listener
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in, check if email is verified
    if (user.emailVerified) {
      console.log('Email is verified');
      console.log(user);
      // Allow access to your protected content here
    } else {
      // Email not verified: sign out and redirect
      alert("Please verify your email before accessing this page.");
      firebase.auth().signOut()
        .then(() => {
          window.location = "index.html";
        });
    }
  } else {
    // No user signed in, redirect to login/sign-up
    window.location = "index.html";
  }
});

Key Notes

  • Always handle Firebase auth methods with .then()/.catch() or async/await to ensure you're working with valid user objects after operations complete.
  • When redirecting after sign-out, wrap the window.location call inside the signOut() promise's .then() to make sure the sign-out finishes first.
  • You might want to add a dedicated "check your email" page instead of just alerting, to improve user experience.

内容的提问来源于stack exchange,提问作者nboris55

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:12