skip to Main Content

I am new to firebase and I am trying to use firestore to get data for my next.js app but get an error.

Here is the error:

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11730:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: AggregateError
      at internalConnectMultiple (node:net:1114:18)
      at afterConnectMultiple (node:net:1667:5)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
  }
}

and here is the code:

import React from 'react';
import { initializeApp } from 'firebase/app'
import {
  getFirestore, collection, getDocs
} from 'firebase/firestore'




const firebaseConfig = {
    apiKey: process.env.API_KEY,
    authDomain: "social-app-a0aef.firebaseapp.com",
    projectId: "social-app-a0aef",
    storageBucket: "social-app-a0aef.appspot.com",
    messagingSenderId: "106093296170",
    appId: "1:106093296170:web:852948bb8d8fd86ccfe153"
  };

// init firebase
const app = initializeApp(firebaseConfig)

// init services
const db = getFirestore(app)

// collection ref
const colRef = collection(db, "books")

// get collection data


async function Firebase() {

    try {
        const snapshot = await getDocs(colRef)
        snapshot.forEach((doc) => {
            console.log(doc.data)
        })
    } catch (err) {
        console.error("firebase error:", err)
    }

    

  return (
    <div></div>
  )
}

export default Firebase

I checked the .env.local file, the database status, and tried to catch detailed error but couldn’t solve the issue.

2

Answers


  1. Chosen as BEST ANSWER

    This code was in a js file (as far as I know, it should've worked for js files) and I tried to make it a component (jsx file) and used it in my page.js file. It worked for some reason.


  2. If you are using NextJS and try to initialize firebase on the client (which you should), you need to access the .env environment variables with a prefixed NEXT_PUBLIC_ Tag.

    Try hardcoding the Api Key in your config to test it out.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search