I'm working on a nuxt project and I use @nuxt/firebase module to login/logout the user and it works fine.
Now i'm trying to verify the id token when a user visits the admin page and do something depending on the result, but I'm stuck on getting the verifyidtoken method to work.
I cant access nuxt.$fire.auth (I can in my plugins for example), I figured it's because this runs on the server so i had to import the packages but i'm not sure this is the optimal way.
I configured the nuxt.config.js to use a module named auth.js
modules/auth /
import cookie from "cookie";
import { initializeApp, applicationDefault } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";
export default function () {
const { nuxt } = this;
nuxt.hook("render:setupMiddleware", (app) => {
app.use("/admin", handler);
});
const handler = (req, res, next) => {
const idToken = cookie.parse(req.headers.cookie)["idToken"];
const fireAuth = initializeApp({
credential: applicationDefault(),
projectId: "testApp",
});
getAuth(fireAuth)
.verifyIdToken(idToken)
.then((decodedToken) => {
console.log(decodedToken);
})
.catch((error) => {
// Handle error
});
next();
};
}
This works for the first time i visit the page. If i reload, it gives me the error that a firebase app is already initialized.
The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.
I dont know how to put a guard clause to see if the app is already initialized. Moreover, I feel that this is not the best approach.