Where to place code to set Firebase auth state persistence in Vue.js?

Viewed 2087

Overview

I'm building a web app in Quasar/Vue.js and Firebase which needs to authenticate users.

What I'm trying to achieve

A pretty common feature - keep users logged even after they close the browser/tab.

Possible Solutions

I'm aware that I can use localStorage or cookies to set the user auth state. However, I want to allow Firebase auth do it for me (if it can do it).

I checked the docs in this regard - https://firebase.google.com/docs/auth/web/auth-state-persistence and they're nice, except I cannot figure out where to place this piece of code mentioned there:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
  .then(function() {
    // New sign-in will be persisted with session persistence.
    return firebase.auth().signInWithEmailAndPassword(email, password);
  })
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

I'm not sure where to place it out of the following places:

  • with the onAuthStatechanged listener?
  • in the App.vue (root Vue) instance?
  • somewhere else?

Would be glad if anyone could help out. Thanks.

1 Answers

I'd do it wherever you have firebase.initializeApp(). Eg

firebase.initializeApp({
  // config goes here
});

export const auth = firebase.auth()

auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)

Note that LOCAL is the default in web apps already.

You don't really need to wait for that promise. From the docs

This will return a promise that will resolve once the state finishes copying from one type of storage to the other. Calling a sign-in method after changing persistence will wait for that persistence change to complete before applying it on the new Auth state.


The modular version (v9+) of this would look like the following...

import { initializeApp } from "firebase/app";
import {
  browserLocalPersistence,
  getAuth, 
  setPersistence
} from "firebase/auth";

const app = initializeApp({
  // config goes here
})

export const auth = getAuth(app);

setPersistence(auth, browserLocalPersistence)
Related