Discovering the process of retrieving information from Firebase using getServerSideProps in NextJs

I've been exploring ways to retrieve data from Firebase within GetServerSideProps in NextJs

Below is my db file setup:

import admin from "firebase-admin";
import serviceAccount from "./serviceAccountKey.json";

if (!admin.apps.length) {
  try {
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
    });
  } catch (error) {
    console.log("Firebase admin initialization error", error.stack);
  }
}
export default admin.firestore();

Next, I use getServerSideProps to fetch the data:

export async function getServerSideProps(context) {
  const id = context.params.profileId;
  const doc = await db.collection("profile").doc(id).get();
  const profile = doc.data();
  return {
    props: { profile },
  };
}

An error message appears saying:

error - ./node_modules/@google-cloud/storage/build/src/bucket.js:21:0
Module not found: Can't resolve 'fs'

I'm wondering if there's an alternative method to interact with Firebase that doesn't rely on a Node Library requiring access to the filesystem. Any suggestions or workarounds would be greatly appreciated.

Thank you!

Answer №1

If you are utilizing the firebase-admin package, it can only be used in API functions and cannot be imported on the client side due to its reliance on the fs module which is unavailable there. For client-side Firebase usage, consider using the @firebase/app npm module.

import { initializeApp, getApps } from 'firebase/app'
import { getAnalytics } from 'firebase/analytics'
export const createFirebaseApp = () => {
  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,
  }

  if (getApps().length <= 0) {
    const app = initializeApp(clientCredentials)
    // Check that `window` is in scope for the analytics module!
    if (typeof window !== 'undefined') {
      // Enable analytics. https://firebase.google.com/docs/analytics/get-started
      if ('measurementId' in clientCredentials) {
        getAnalytics()
      }
    }
    return app
  }
}

You may have two separate Firebase configuration files: one for client-side using the above approach, and another for utilizing firebase-admin as specified.

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

Creating Transparent Rounded Backgrounds in Google Chrome Packaged Apps: Achieving the same look as Google Hangout app

Looking at the screenshot below, it is evident that the Hangout app has a fully transparent design with background shadow effect applied to it. I have tried various methods in vain, such as applying CSS styling to the "html" and "body" tags of the page, a ...

Is there a way to create a reusable HTTP response handler for Node.js applications?

As I work on creating a rest api for a node application, I often find myself repeating the same code structure: function(req, res, next) { databaseCall() .then( (results) => { if (results != null) { res.status(200).send(results); } el ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

Harnessing the Power of Google Tag Script in Next.js

After researching How to load Google Tag Manager with the next/script component (Next.js 11) and reviewing this documentation page, my issue remains unresolved. I am looking to implement Google Tag on multiple websites developed using nextjs, so I created ...

Preventing click events with pointer-events property in CSS while still allowing scrolling

Is there a way to use pointer-events: none to disable click events on a specific container while still allowing scroll functionality and an overlay? You can view my fiddle here: https://jsfiddle.net/1eu6d3sq/1/ Currently, when I apply pointer-events: non ...

Pressing the enter key does not submit the Vue.js form

When attempting to submit the form by pressing "enter" on the keyboard, it only works when I click the "submit" button. I made sure to add @submit to the form event to ensure it triggers, but upon checking a log, I found that it only triggers when clicking ...

Updating line connections between objects in Three.js while rendering

I am working with a three.js canvas that contains circles moving independently. Initially, these circles are connected by a single line that follows the same geometry as their positions. However, I am facing difficulty updating the line's geometry wh ...

What is the best way to retrieve information in Next.js when there are changes made to the data, whether it be new

Could you share a solution for fetching data in Next.js when data is added, deleted, or edited? I tried using useEffect with state to trigger the function but it only works when data is added. It doesn't work for edit or delete operations. I have mult ...

Looking for a specific item on the Shopify Storefront API? Start your

I am currently working on an eCommerce App using Next.js and Shopify Storefront API. I am facing an issue with filtering all the products in the Shopify Database. This feature is crucial for implementing a search bar that can display relevant products base ...

Learn the art of animating "basic jQuery filtering" exclusively with CSS

Does anyone have suggestions on how to animate elements when filtered by JavaScript? The code I've tried so far doesn't seem to be working. Here's what I currently have: http://jsfiddle.net/ejkim2000/J7TF4/ $("#ourHolder").css("animation", ...

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

Is it possible to load multiple angular applications within a master angular shell application?

I am searching for a method to integrate multiple Angular applications into a single shell Angular application. The concept involves having different teams develop separate Angular apps that can be loaded within a main shell app visible to end users. Thi ...

"Can you guide me on how to display a React component in a

I have a function that loops through some promises and updates the state like this: }).then((future_data) => { this.setState({future_data: future_data}); console.log(this.state.future_data, 'tsf'); }); This outputs an array o ...

Displaying JSON data in an HTML table cell format

Hey everyone, I need some help with the following task: I am working on displaying a list of log lines in an HTML table. Some of these lines will contain JSON strings, and I want to format the JSON data within the table when the HTML file is loaded from ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Use the colResize function in R Shiny to establish communication and synchronize the column sizes between R and

I'm currently using a plugin called datatables.colResize to allow manual column resizing for DataTables in my R Shiny application. My goal now is to save the column width state once a user adjusts the table size. I want this information to be passed a ...

The link in the drop down select is not functioning in IE8/9. When trying to open the drop down select link, an

Could use some help with IE8 and 9 compatibility, can't seem to find a solution. This code works smoothly on Chrome, FF, and Safari. There are two dropdown menus, each with two links. Every dropdown menu has its own "Buy Now" button. Upon selecting ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this: <template> // content irrelevant </template> <script> export default { data() { return { redLocations: [ "Isfahaan", "Qom", ...