Exploring the integration of Firebase with Next.js using getServerSideProps

I'm trying to retrieve the 'sample' document from Firestore using getServerSideProps only if a user is signed in. However, the current code I have isn't working and just returns 'can't read'. Is there a better solution or something I should be doing differently?

export const getServerSideProps = () => {
  let currentUser = []

  authService.onAuthStateChanged(async user => {
      if(user) {
        const docRef = dbService.collection('whole_users').doc('sample').get()
        await docRef.then(doc => {
          if(doc.exists) {
            currentUser.push(doc.data())
          }
        })
      } else {
        console.log("can't read")
      }
    })

  return {
    props: {currentUser}
  }
}

Answer №1

Firstly: Attempting to call get() without using an await. Revise your code as shown below:

export const getServerSideProps = () => {
  let currentUser = []

  authService.onAuthStateChanged(async user => {
      if(user) {
        const docRef = dbService.collection('whole_users').doc('sample')
        await docRef.get().then((doc) => {
          if(doc.exists) {
            currentUser.push(doc.data())
          }
        })
      } else {
        console.log("Unable to retrieve data")
    }
  })

  return {
    props: {currentUser}
  }
}

Secondly: The onAuthStateChanged method is intended for client-side use only. To access the authentication state on the server side, you must incorporate the auth state into a provider. Refer to this resource for guidance.

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

Incorporate external library source maps into your Webpack configuration

I'm currently working on a NextJS project that relies on a 3rd party library. This library comes with a source map file packaged as part of its NPM package, consisting of two files: lib.mjs lib.mjs.map However, after building my project, I've n ...

Tips on converting HTML code into a data image URI

My question may seem unconventional, but here is what I am trying to accomplish. I want to create a design similar to the one found at the following link: I would like to embed text with an image and retrieve the data image URL using Ajax. I know how to g ...

jQuery UI's $(...).sortable function is throwing an error when being used with WebPack

After setting up everything correctly, I encountered an unusual issue with Webpack. Let's take a look at this simple app.ts file: 'use strict'; import $ = require('jquery'); import 'jquery-ui'; $(function() { $( " ...

What is the best way to instantly validate a form in React before submitting?

Having trouble with my form validation. The issue is that after validating the form on submit, I have to click the submit button a second time to actually send it and see the console.log at the bottom of the file. Any ideas on what might be causing this a ...

Summon wicket from the non-wicket-component entity

I am currently utilizing js-lib to transform text into a rich-editor, complete with options such as "bold", "italic" and more. The RichEditor also includes an UploadImage button, for which I am able to modify the call-back function: function startUploadi ...

Transforming Material UI into a class-based component

How can I transform a React function into a class? I'm having trouble understanding how to adjust const { classes } = props; in a function to work within a class. You can find an example button function from Material UI here: import React from &apos ...

A guide to managing Ajax in functional components in React without using classes

Currently, I am striving to develop all my components as pure functions. However, I have encountered an issue. The component I am working on resembles the structure below. The problem arises when the result of an ajax request triggers a rerender, leading ...

The range filter is exclusive to the initial controller

My range filter (see code below) is only working on my first controller. I have added the same filter to other controllers in the app.js and HTML, but it's not functioning for some reason. I checked the console for errors, but there are none. Here i ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

The property number will have no effect on the time

Currently, I am in the process of developing an audio player that includes essential functions such as backward, play, and forward buttons. Strangely enough, the backward function operates perfectly fine, but the forward button is not functioning properly ...

Leveraging webpack for requiring modules in the browser

I've been attempting to utilize require('modules') in the browser with webpack for the past couple of days, but I could achieve the same functionality with browserify in just 5 minutes... Below is my custom webpack.config.js file: var webp ...

Using Firebase to interact with data: $add(), .push(), and .set()

Utilizing Firebase and AngularFire has opened up many different approaches for CRUD operations with the Firebase API. However, I am still uncertain about the specific differences between using: $add with $firebaseArray The .push() method The .set() metho ...

What are the connections between objects in ReactJS?

I have an array containing objects, and I want to extract a specific value from another array by using the key inside it as a search parameter. Specifically, I need to retrieve the name of an item based on its ID. The primary array: this.setState({ offer ...

Dynamic Checkbox Functionality in REACT

Motivation: My goal is to generate multiple rows with a variable number of checkboxes that will be managed by a useState hook. Challenge: The page freezes or displays constant loading, with no content visible. There are no console logs, and even the debug ...

Populating dropdown menu with data fetched from an AJAX request

I've created a dropdown in my cshtml page: @( Html.Kendo().DropDownList().Name("ddlCode").OptionLabel("Select Code...").BindTo(@ViewBag.dropDown) .DataTextField("Title") .DataValueField("domainCode") The dropdown is bound up ...

Identify the key name in an array of objects and combine the corresponding values

Here is an example of my array structure: array = [{ "name": "obj0_property0", "url": "picture1" }, { "name": "obj1_property0", "url": "picture1" }, { "name": "obj0_property1", "url": "picture2" }] I am looking to transform this array using J ...

What could be causing my state not to change in Nextjs even though I followed the quick start guide for Easy Peasy?

I recently encountered an issue while trying to implement easy peasy for global state management in my nextjs app. The problem I faced was that the state would only update when I changed pages, which seemed odd. To better understand what was going on, I de ...

Errors in vue.js conditions

I am currently attempting to validate whether my variable is empty. Despite reviewing my code, I am facing issues with its functionality. My current version of vue.js is 2.5.13 Below you can find the snippet of my code: <template> <div v-if ...

What causes the occurrence of "undefined" after multiple iterations of my code?

I've encountered a curious issue with the code snippet below. Everything seems to be running smoothly except for one thing - after a few iterations, I start getting "undefined" as an output. You can test this for yourself by running the code multiple ...

AngularJS binding variables to HTML tag attributes

Currently, I am going through the tutorials and documentation for Angularjs that is provided on the official Angularjs website. One of the examples involves adding a select box for ordering which looks like this: <select ng-model="orderProp"> ...