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

Trouble with Font registration in react-pdf within NextJS framework

When I created a React application, I successfully used the package and imported my own fonts like this: import PrometoRegular from '../../assets/fonts/Prometo-Regular.ttf'; // Register font Font.register({family: 'PrometoRegular', sr ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

The data retrieved from Firebase is coming back as not defined

I am currently working on an Angular component that is designed to showcase data retrieved from Firebase in a table using a service: <table class="table table-sm"> <thead> <th>Animal Name</th> <th>Species</th> ...

Next.js 14.0.4 is encountering an ENOENT error due to the absence of the BUILD_ID file

My Next.js 14.0.4 project is running into an ENOENT error due to the missing BUILD_ID file, here are some specifics about my project: Node.js version: 21.5.0 Next.js version: 14.0.4 [email protected] start next start ▲ Next.js 14.0.4 Local: ...

Troubles with creating promises in Node.js

Currently, I am facing a challenge in Nodejs where I need to execute asynchronous tasks. Specifically, I need to navigate through all levels of a JSON object sequentially but synchronously. I am experimenting with the following code snippet, which is a si ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

Having trouble parsing the JSON object values within the Error section of the Ajax call

When making an Ajax call to a rest web API, I encountered an error that I need help resolving. Here is the code snippet: $.ajax({ url: "/********/getbytitle('****')/items", type: "POST", contentType: "applicat ...

GET method returns an empty array in the express node server

app.get('/:user/:tag', function (req, res) { fs.readdir( 'api'+path.sep+req.params.user, function (err, files) { var tweets=[]; for (var i =1, j=files.length ; i <j; i++) { fs.readFile('api'+path.sep+ ...

The destroy method of Chart.js does not appear to have any impact on the

Hello, I've come across this issue in my react app that I need help with: this.chart = new Chart(node, options); // adding data to the chart ... this.chart.destroy(); this.chart = null; this.chart = new Chart(node, options); // adding data to the cha ...

Encountering a "400 Bad Request" error when using Ajax within WordPress

I've been trying to submit a form using Ajax within a plugin. I had two plugins, the first one was initially working but has stopped now and I can't seem to find any errors. I don't think the issue lies in the code itself, but I'm feeli ...

A step-by-step guide on executing a callback function once the animation has finished with frame-motion

I'm facing an issue with my component called AnimatedText. After the animation is complete, I want the words filled in the underlineLines prop to be underlined. How can I achieve this? I attempted using the onAnimationEnd function, but it didn't ...

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

The straightforward splitting of a string is yielding an object rather than an array

Attempting a simple string split in NodeJS is resulting in an unexpected outcome where it returns an object instead of an array. var mytext = "a,b,c,d,e,f,g,h,i,j,k"; var arr = mytext.split(","); console.log(typeof mytext); <======= output string conso ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

Implementing a jQuery change event to filter a specific table is resulting in filtering every table displayed on the page

I have implemented a change event to filter a table on my webpage, but I am noticing that it is affecting every table on the page instead of just the intended one. Below is the code snippet: <script> $('#inputFilter').change(function() { ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

Creating a function in Angular to locate each object based on its ID

Hello there, I am currently working on creating a method called findChildByIdInData(data:any, childId:string). This method will take in a JSON main node with children that have unique IDs, and the goal is to find a specific object based on the ID provided ...

Can the typical drag and drop cursors be ignored in an HTML drag operation?

I've been working with the HTML drag and drop API to allow users to resize columns in a table. However, I've noticed that when a user starts dragging a column, the cursor changes to one of the default drag and drop effects (such as move or none). ...