skip to Main Content

I’m trying to create PWA application using Vue 3 and Firebase. One of my must have featues it to provide offline support, that includes keeping the user logged in even while his internet connection is down.

So long story short, let’s start with firebase.ts setup

export const firebaseApp = initializeApp(firebaseConfig)
export const db = getFirestore()
export const auth = getAuth(firebaseApp)

enableIndexedDbPersistence(db)
    .catch(err =>  alert(err)); 

Then, I have an action that is executed to login user

async login(context, {email, password}) {
    const response = await signInWithEmailAndPassword(auth, email, password)

    if (response) {
        context.commit("setAuth", response.user)
    }
}

As far as I understand documentation and different sources, with that simple setup, auth should be persisted offline.

So I’ve added test code to my app

<VMain>
  <VBtn @click="check">Check</VBtn>
  {{ userInfo }}
  <RouterView class="pa-6"/>
</VMain>

import {auth} from "@/plugins/firebase";
import {ref} from "vue";

const userInfo = ref("")

async function check() {
  const user = auth.currentUser
  if (user) {
    userInfo.value = user.uid
  } else {
    userInfo.value = "logged out"
  }
}

And it seems to be working, I launched my app on my iPhone, I’ve added it to home screen, I logged in and then I turned off network on my phone.

I was able to use my app, navigate between different views and function referenced above was always returning logged user ID. I could minimalize my app and after getting back there it was still working. But, once I removed app from running in background and after reopening it again, I was logged off. Is there a way to avoid that and keep user logged in even if:

  • he is offline
  • he completely closed the app (removed from background on IOS)

I have 2 ideas how to accomplish that:

  1. Storing tokens in localStorage and then using them to login on app startup, but I guess that would require internet connection as well?
  2. If that’s the case, I can just assume that if token exists in localStorage, that means that user is logged in. Then, once internet connection is back, I can use those tokens to re-authenticate user

The question is – am I overcomplicating things? Maybe there is other, better and ready to use solution?

2

Answers


  1. Use firebase onAuthStateChanged listener and save the value in your store.

    onAuthStateChanged(auth, () => {
      const store = useStore();
      store.setUser(auth);
    });
    

    Whenever the user’s auth state changes it will update the store accordingly.
    You can then leverage Vue reactivity to update the UI accordingly.

    As far as the PWA aspect – you will need to be online to load the app initially, of course. Once the app is loaded and the user auth is saved in the store it is no problem if the app goes into the background and is offline. You will be able to open the app and use it just the same as if you never left the app, providing the time elapsed is short enough. My experience is that after about 6 hours give or take it will require full reload and you will need to be online at that point. This is based on my experience. Hope it helps!

    Login or Signup to reply.
  2. Same as Firestore the Authentication has its own function to turn on persistence.

    import { getAuth, setPersistence, signInWithEmailAndPassword, browserSessionPersistence } from "firebase/auth";
    
    const auth = getAuth();
    setPersistence(auth, browserSessionPersistence)
      .then(() => {
        // Existing and future Auth states are now persisted in the current
        // session only. Closing the window would clear any existing state even
        // if a user forgets to sign out.
        // ...
        // New sign-in will be persisted with session persistence.
        return signInWithEmailAndPassword(auth, email, password);
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
      });
    

    More in doc

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search