How to use firestore emulator with Nextjs

Viewed 1906

I'm trying to use Firebase Emulator on a local project based on Nextjs. Following the guidance from Firebase here I'm trying to use db.useEmulator('localhost', 8080); after I initialised Firebase but I have this error:

Error was not caught TypeError: db.useEmulator is not a function
  at Module.eval (VM79706 firebase.js:30)
  at eval (VM79706 firebase.js:91)
  at Module../utils/firebase.js (_app.js?ts=1603918354205:23994)
  ...

I've been using the emulator to test cloud functions and it's working pretty well. I just don't understand how to connect it with Firestore.

Here is how I set up Firebase:

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';
import 'firebase/analytics';

const clientCredentials = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
  measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};

// Check that `window` is in scope for the analytics module!
if (typeof window !== 'undefined' && !firebase.apps.length) {
  firebase.initializeApp(clientCredentials);
  if ('measurementId' in clientCredentials) firebase.analytics();

  const db = firebase.firestore();
  if (process.env.NEXT_PUBLIC_DB_HOST === 'localhost') {
   db.useEmulator('localhost', 8080);
  }
}

export default firebase;

Any idea why I'm getting this error and how I connect Firebase emulator with Nextjs?

2 Answers

To answer my own question, the problem was that this method was introduced in the new version of firebase 8.0.0. I just had the update and voila!

Using firebase ver. 9.4.1. You may using database UI for work with database locally. Url to database UI show, when start emulators. Regular url: localhost:PORT/database

Related