Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA.

These errors keep popping up:

index.js // main Firebase file

import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore'
import { getStorage } from 'firebase/storage'

const firebaseConfig =
  process.env.NEXT_PUBLIC_FIREBASE_CONFIG

const app = initializeApp(JSON.parse(firebaseConfig))
export const db = getFirestore(app)

// enableIndexedDbPersistence(db) //   >>>  if put here it said can't be invoked after getFirestore or any other funtion

export const auth = getAuth(app)
export const storage = getStorage(app)

Where should I invoke this function?

Answer №1

Before doing anything else, remember to call the function enableIndexedDbPersistence(db). Here's what the documentation says:

This function must be called before any other functions (except for {@link initializeFirestore}, {@link (getFirestore:1)}, or {@link clearIndexedDbPersistence}.

However, it seems that the function getFirestore(app) is an exception to this rule, despite what you may have thought based on your comment in the code snippet:

// >>> if put here it said can't be invoked after getFirestore or any other function

It appears that you may be trying to use the exported db variable before the promise from enableIndexedDbPersistence(db) has finished. To fix this, consider wrapping the code in a service or method and ensuring that you are using await with the promise, or structuring your app so that db isn't immediately accessed.

In my Ionic PWA application, I've successfully implemented the following approach:

import { getFirestore, enableIndexedDbPersistence } from "firebase/firestore";
import { initializeApp } from "firebase/app";

const firebaseConfig = {
  // ...
};

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

enableIndexedDbPersistence(db)
    .then(() => console.log("Enabled offline persistence"))
    .catch((error) => {
      if (error.code == "failed-precondition") {
        // Multiple tabs open, only one tab can enable persistence at a time.
        // ...
      } else if (error.code == "unimplemented") {
        // The current browser does not support all the necessary features for persistence
        // ...
      }
    });

While this setup may resemble yours, the key difference is that Firestore is first accessed in response to user interaction, rather than immediately.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Errors during the compilation of Webgl shaders in the Google Chrome browser

Currently, I am in the process of learning three.js by following this tutorial: . Despite the tutorial working well, I have encountered errors in my own code which seem like this: ERROR: 0:26: 'nuniform' : syntax error Three.js:325 precision hi ...

Utilizing Multi External CDN JavaScript File with Vue CLI Component: A Comprehensive Guide

I've been trying different methods to include external JS files in a Vue Component, such as using mounted() and created(), but unfortunately, none of them have worked for me so far. I'm not sure where I'm going wrong. Any assistance would be ...

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...

Seeking to duplicate script for a new table without making any changes to the original script

I am working with two tables that require the capability to dynamically add and delete rows using separate scripts. How can I modify the second script so that it only affects the second table and not the first one? Table: <table id="myTable" class=" t ...

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

tips for transferring API JSON response parameters to material ui table

I'm currently working on creating a table with the material UI. My goal is to populate the rows of the table based on the data received from an API response. The challenge I'm facing is that the API response includes an array of objects with mult ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

Transferring information from the backend (powered by nodejs) to the frontend using JavaScript

I have data stored in my MongoDB database and I am retrieving this data from the DB to save it to an array. When a button is clicked on the webpage, I want to send this data to my JavaScript file and use the DOM to display it on the page. On page load, I ...

Footer on webpage remains at bottom of screen even while scrolling

After creating a web footer, I expected it to appear only when reaching the bottom of the page. However, it remains fixed at the bottom of the screen and takes up half of the display space. The footer on my react website is not functioning as intended. Al ...

In JavaScript/jQuery, there is a technique for retrieving the values of dynamically generated td attributes and the id tags of elements inside them within tr

I am currently working on creating a calendar of events using PHP, jQuery, and ajax. The calendar is embedded within an HTML table, where the rows and fields are dynamically generated based on the number of days in a specific month. In order to successfull ...

Is there a way to confine a jquery script within the dimensions of the container div?

I have recently created a gallery with navigation buttons in jQuery. As a newcomer to jQuery, I wrote a small script that adjusts the margin of a div container by a fixed amount. The script is functioning properly, but it extends beyond the top and bottom ...

The ASP.NET Core MVC controller encounters a null input parameter when called by an ajax request

Here is the scenario involving an ajax call: ... $("#testBtn").click(function (e) { e.preventDefault(); $.ajax({ url: "/profile/GuestList", data: {"keytype": "1"}, method: "POST&q ...

VueJS Components experiencing issues with displaying images

Recently, I delved into learning VueJS and successfully created a basic restaurant menu page all within a single file. Excited by my progress, I decided to refactor the project using vue-cli, but hit a snag with the images not displaying properly. The cur ...

Tips on utilizing the getElementsByClassName method in JavaScript

Check out this HTML snippet: <html> <body> <div id="wrapper"> <div id="c_wrapper"> <div class="member"> <form name="f1"> </form> </div> ...

Having trouble uploading my confidential npm package to a secure Nexus repository

I have my own personal collection of books and I am looking to share it by publishing an npm package to a private Nexus registry Here is my package.json setup { "name": "@uniqueorganization/the-collection", "version": ...

Clerk and Vitest Errors in Unit Testing

Currently, I am tackling a project at my workplace that has a strict requirement for unit tests. To fulfill this requirement, I opted to utilize Vitest and integrated Clerk for authentication purposes. However, I've encountered two distinct issues alo ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...