0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Auth State Persistence in Firebase

Use setPersistence() on the Firebase Auth instance to control how the user's authentication state is saved. Choose from local (persists across tabs and sessions), session (persists only in the current tab), or none (no persistence). This ensures users stay signed in as you want.
📐

Syntax

The setPersistence() method on Firebase Auth sets how the user's sign-in state is stored.

  • firebase.auth.Auth.Persistence.LOCAL: Saves state in local storage, keeping users signed in across browser tabs and sessions.
  • firebase.auth.Auth.Persistence.SESSION: Saves state in session storage, keeping users signed in only in the current tab.
  • firebase.auth.Auth.Persistence.NONE: Does not save state, so users sign out when the page reloads.
javascript
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
  .then(() => {
    // Now sign in the user
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch((error) => {
    console.error('Error setting persistence:', error);
  });
💻

Example

This example sets auth state persistence to LOCAL so the user stays signed in across browser sessions. It then signs in a user with email and password.

javascript
import { initializeApp } from 'firebase/app';
import { getAuth, setPersistence, signInWithEmailAndPassword, browserLocalPersistence } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

setPersistence(auth, browserLocalPersistence)
  .then(() => {
    return signInWithEmailAndPassword(auth, 'user@example.com', 'userPassword');
  })
  .then((userCredential) => {
    console.log('User signed in:', userCredential.user.email);
  })
  .catch((error) => {
    console.error('Error:', error.code, error.message);
  });
Output
User signed in: user@example.com
⚠️

Common Pitfalls

Common mistakes include:

  • Not calling setPersistence() before signing in, which means the default persistence is used.
  • Using NONE persistence unintentionally, causing users to sign out on page reload.
  • Confusing SESSION and LOCAL persistence, leading to unexpected sign-out behavior when switching tabs.

Always handle errors from setPersistence() to catch unsupported browsers or other issues.

javascript
/* Wrong: Setting persistence after sign-in */
const auth = getAuth();
signInWithEmailAndPassword(auth, 'user@example.com', 'password')
  .then(() => {
    return setPersistence(auth, browserLocalPersistence); // Too late
  })
  .catch(console.error);

/* Right: Set persistence before sign-in */
setPersistence(auth, browserLocalPersistence)
  .then(() => signInWithEmailAndPassword(auth, 'user@example.com', 'password'))
  .catch(console.error);
📊

Quick Reference

Persistence TypeDescriptionStorage Location
LOCALKeeps user signed in across tabs and browser restartsLocal Storage
SESSIONKeeps user signed in only in current tabSession Storage
NONEDoes not persist user state; signs out on reloadMemory (no storage)

Key Takeaways

Always call setPersistence() before signing in to control auth state saving.
Use LOCAL persistence to keep users signed in across browser sessions.
SESSION persistence keeps users signed in only in the current tab.
NONE persistence means users sign out on page reload or tab close.
Handle errors from setPersistence() to ensure compatibility.