The latest version of Cloud Firestore Web (version 9) is not compatible with NextJs getServerSideProps for

In my current project, I am utilizing NextJs version 12.0.10 along with firebase version 9.6.6, both of which utilize a modular system for imports.

However, when attempting to run the function in my service that fetches data from firebase/firestore, an error is returned stating

Cannot access 'getStories' before initialization
. Despite being confident in the correctness of the logic and syntax, the issue persists. Strangely enough, everything works perfectly fine when fetching within the page render function.

Below is the snippet of my getServerSideProps function found in pages/index.js:

import '@uiw/react-markdown-preview/markdown.css';
import { useContext } from 'react';
import { getStories } from '../lib/services/StoryService';
import { truncate } from 'lodash';
import { convertSecondsToHumanReadableDiff } from '../lib/utils/common';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { AuthContext } from '../pages/_app';
import Navigation from '../components/Navigation';

export async function getServerSideProps() {
  const fetchedStories = await getStories();

  const stories = fetchedStories.docs.map((story) => {
    return {
      ...story.data(),
      id: story.id,
      content: truncate(story.data().content, { length: 150, separator: '...' }),
    };
  });

  return { props: { stories } };
}

const Blog = ({ stories }) => {
  const router = useRouter();
  const { user } = useContext(AuthContext);

  return (
    <div>
      ...
    </div>
  );
};

export default Blog;

lib/firebase/firebase.js

import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'XXX',
  authDomain: 'XXX',
  projectId: 'XXX',
  storageBucket: 'X',
  messagingSenderId: 'XXX',
  appId: 'XXX',
  measurementId: 'XXX',
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

export const database = getFirestore(app);
export const auth = getAuth(app);

lib/services/storyService.js

import {
  collection,
  query,
  getDocs,
  getDoc,
  setDoc,
  doc,
  serverTimestamp,
  orderBy,
} from 'firebase/firestore';
import { database } from '../firebase/firebase';
import slugify from 'slugify';
import { random } from 'lodash';

const storiesRef = collection(database, 'stories');

export const createStory = async (payload) => {
  const slugTitle = slugify(payload.title);
  const slug = slugTitle + '-' + random(0, 100000);
  const updatedPayload = {
    ...payload,
    slug,
    type: 'published',
    createdAt: serverTimestamp(),
  };

  return setDoc(doc(storiesRef, slug), updatedPayload);
};

export const getStories = async () => {
  const q = query(storiesRef, orderBy('createdAt', 'desc'));

  return getDocs(q);
};

export const getStoryBySlug = async (slug) => {
  const docRef = doc(database, 'stories', slug);

  return getDoc(docRef);
};

https://i.sstatic.net/aOtd6.png

Answer №1

When working with Firebase, make sure to use the appropriate SDK for your environment. If you're using client-side functions like getDocs within a function that gets invoked on the server side (such as in getServerSideProps in a node.js environment), you should be using the admin SDK instead.

Here's an example of how you can refactor your code to use the admin SDK:

    import * as admin from "firebase-admin/firestore";
    
    export const getStories = async () => {
     return await admin
      .getFirestore()
      .collection(database, 'stories')
      .orderBy('createdAt', 'desc')
      .get()
    };

    export const getStoryBySlug = async (slug) => {
     return await admin
      .getFirestore()
      .doc(database, 'stories', slug)
      .get()
    };

(Apologies for the delayed response, but I hope this information proves helpful to OP or anyone else facing a similar issue)

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

Adding the Load More feature to your WordPress template for displaying custom posts

On my website, I am retrieving posts of a custom post type using get posts. However, I am retrieving all posts at once, but in my template, I want to display x number of posts per page and load the remaining posts using a load more button. <?php ...

Tips for transferring JSON information instead of displaying it in the console

Currently developing a food ordering application using Flutter along with an API built in Express.js and MySQL for the database. I have successfully connected to the database, received JSON data, and logged it using console.log(), but I am struggling with ...

The console log is not being displayed in my Redux reducer and it is returning an undefined

I'm facing an issue with my Redux application after integrating JWT into my Nest API. Below is the code snippet from my reducer: export default function reducer(state = {}, action) { switch (action.type) { case 'USER_LOGIN_SUCCESS&apo ...

Is it possible in ReactJS to return JSX from a callback function?

After spending some time working with react, I encountered a basic issue that has me stumped. In the Login component, I am submitting a form and if it returns an error, I want to render a snackbar message. handleSubmit = (event) => { event.preven ...

The default action is not triggered when the click event occurs

Hey there, I have been working on this <ol> list of events using jQuery (version 1.4.2). Everything is set up within the $(document).ready() function. Something strange is happening where when I click on the <li>, it triggers a click on the co ...

Is it possible for PHP to use the set cookie function to replace the cookie value set by JQuery cookie?

I'm facing an issue where I want a single cookie to be set and its value updated by PHP when a user logs in. However, currently it seems to just create a new separate cookie each time. Below is the code snippet where I am trying to set the cookie valu ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...

Utilize Middleware for targeted next-connect paths within a single file containing multiple routes

While working with next-connect, I am interested in implementing a yup validation middleware for a specific route (post) only. However, the file containing this route also includes other routes such as get and put. Is there a way to apply the yup validatio ...

Unable to retrieve parameter while making a POST request

Need some help with attribute routing. I'm having trouble getting parameters from the HTTP body. The ConnectionID Class includes a property named CValue. $('#btn').click(function () { $.ajax({ type: "POST", url: "http:// ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

How can the edit feature be implemented in AngularJS?

I am struggling with implementing an edit field in AngularJS. Can someone please help me with this? Here is the code for my CRUD operations: var app = angular.module('myApp', []) app.controller('myCtrl', ['$scope', functio ...

Generating variables dynamically within a React Native component

In my React Native component, I need to create a variable that will be used multiple times. Each instance of this component should have a different variable name for reference. <View ref={view => { shapeView = view; }} onLayout={({ nativeE ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

Is there a way to prevent Material-UI SpeedDial from automatically closing when a SpeedDialAction button is clicked?

Looking to customize the functionality of Material-UI's SpeedDial component (https://material-ui.com/api/speed-dial/). At present, when a SpeedDialAction is clicked, the main SpeedDial component automatically closes. I want to modify this behavior s ...

Please enter either a single digit or multiple digits that are all the same

In my Vue.js project, I am working on a custom input field component that should only accept positive integers (including 0). Rather than using regex for validation, I prefer to keep the code human-readable :) The parent component that utilizes this input ...

I'm curious, does a specific event get triggered when an item is added to a UL element?

Is there an event that gets triggered when a new item is added to a UL list? I am on the lookout for something like this. Thank you! ...

Searching the JSON file by its value using Waterline

I am struggling with locating model instances based on the nested address attribute in one of my models. attributes: { address: { type: 'json' } } I have attempted various queries to find model instances located in the same city: Model ...

Issues encountered with jQuery's $.ajax function when communicating with PHP

I am having trouble creating a simple app that displays data from a MySQL database using PHP and jQuery. The issue I am facing is with retrieving the data using jQuery. While my PHP script successfully returns the data without any problems, I am not receiv ...

I find it confusing how certain styles are applied, while others are not

Working on my portfolio website and almost done, but running into issues with Tailwind CSS. Applied styling works mostly, but some disappear at certain breakpoints without explanation. It's mainly affecting overflow effects, hover states, and list sty ...